1a = 10
2for i in range(1, 10) # the code will move from the range from 1 to 10 but not including 10
3 print(i)
1#to print number from 1 to 10
2for i in range(1,11):
3 print(i)
4
5#to print a list
6l = [1,2,3,4]
7for i in l:
8 print(i)
9
10r = ["a","b","c","d","e"]
11s = [1,2,3,4,5]
12
13#print two list with the help of zip function
14for p,q in zip(r,s):
15 print(p,q)
1# A for loop in python is used to iterate (or loop) over a sequence.
2# The sequence is usually range(start,end), but can also be a list.
3# Example of for loop with range():
4for num in range(1,10):
5 print(num)
6 # This prints all the numbers from 1 to 10, including 1 but excluding 10.
7
8 # Here is an example of a for loop with a list:
9lst = [1,2,3,4,5]
10for item in lst:
11 print(item)
12 # This prints all items in the list.
13
14# For loops are also used in list comprehensions.
15lst = [1,2,3,4,5]
16new_lst = [item for item in lst if i % 2 == 0]
17# The list comprehension above generates a new list, which new_lst is put equal to.
18# It iterates through the items in lst and only puts them in the new list if it is a multiple of 2.
19
1# Python for loop
2
3for i in range(1, 101):
4 # i is automatically equals to 0 if has no mention before
5 # range(1, 101) is making the loop 100 times (range(1, 151) will make it to loop 150 times)
6 print(i) # prints the number of i (equals to the loop number)
7
8for x in [1, 2, 3, 4, 5]:
9 # it will loop the length of the list (in that case 5 times)
10 print(x) # prints the item in the index of the list that the loop is currently on
1#an object to iterate over
2items = ["Item1", "Item2", "Item3", "Item4"]
3
4#for loop using range
5for i in range(len(items)):
6 print(items[i])
7
8#for loop w/o using range
9for item in items:
10 print(item)