DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

Day 4 of Python(for loop and string methods)

for loop: A for loop is used to repeat a block of code for each item in a sequence like list, tuple,string.

Syntax:

for var in range:
Enter fullscreen mode Exit fullscreen mode

Ex: Print numbers from 1 to 10

for i in range(1,11):
   print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

1
2
3
4
5
6
7
8
9
10
Enter fullscreen mode Exit fullscreen mode

Reverse a string:
To reverse a name,

name = "Vidya"
rev = name[::-1]
print(rev)
Enter fullscreen mode Exit fullscreen mode

Output:

aydiV
Enter fullscreen mode Exit fullscreen mode

To reverse a number,

num = 2356
rev = 0

while num > 0:
    rev = num % 10 + rev * 10
    num = num // 10

print(rev)

Enter fullscreen mode Exit fullscreen mode

Output:

6532
Enter fullscreen mode Exit fullscreen mode

What is list: A list is a collection of items used to store items in single variable. This can store numbers, string. It is a built in data type. It is mutable and classified as ordered and unordered.
Ex:

list = ["apple", "orange","banana","papaya"]
list[0] = "mango"
list[1] = "strawberry"
print(list)
Enter fullscreen mode Exit fullscreen mode

Output:

['mango', 'strawberry', 'banana', 'papaya']
Enter fullscreen mode Exit fullscreen mode

String methods:

  1. append - add one element at the end.
  2. extend - add multiple elements.
  3. insert - insert element at specific index position.
  4. remove - removes the first occurence.
  5. pop - removes and return element.
  6. clear - removes all the elements.
  7. index - returns the index value.
  8. count - count the number of occurence.
  9. sort - sort list in place.
  10. reverse - reverse in place.

Top comments (0)