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:
Ex: Print numbers from 1 to 10
for i in range(1,11):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
Reverse a string:
To reverse a name,
name = "Vidya"
rev = name[::-1]
print(rev)
Output:
aydiV
To reverse a number,
num = 2356
rev = 0
while num > 0:
rev = num % 10 + rev * 10
num = num // 10
print(rev)
Output:
6532
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)
Output:
['mango', 'strawberry', 'banana', 'papaya']
String methods:
- append - add one element at the end.
- extend - add multiple elements.
- insert - insert element at specific index position.
- remove - removes the first occurence.
- pop - removes and return element.
- clear - removes all the elements.
- index - returns the index value.
- count - count the number of occurence.
- sort - sort list in place.
- reverse - reverse in place.
Top comments (0)