# Iterating through a string val = "123456789" total = 0 for x in val: total += int(x) print(total) # 45
# Iterating through a list colors = ["Red", "Blue", "Yellow", "Green"] for color in colors: print(color) # Red # Blue # Yellow # Green
for number in range(5): print(number) # This program will print numbers from 0 to 5 # Stop number is exclusive in range() function # 0, 1, 2, 3, 4 will be printed in the output
range([start], stop [, step])
Step parameter indicates the increment between numbers in the sequence. This parameter is also optional, if not specified step is 1.
Nested For Loop
mathClass = ["John", "Charlie", "Lindsay", "Kylie"] chemistryClass = ["Leonardo", "Kylie", "Nancy", "Charlie"] for mathStudent in mathClass: for chemistryStudent in chemistryClass: if mathStudent == chemistryStudent: print(mathStudent + " is in both classes.") # Charlie is in both classes. # Kylie is in both classes.
Break, Continue, Pass Statements
pass statements are used in (For/While) loops in Python.
break statement is used to exit the loop,
continue statement is used to skip the current iteration,
pass statement is used when you don’t want to execute a code block. To get detailed information you can read Python Break, Continue, Pass Statements.
Else Statement in For Loops
else statement is used in a For loop, Else code block is executed after for loop execution unless
break statement is run.
for name in phoneDirectory: if name == "John": print("John's phone number is : " + phoneDirectory[name]) break else: print("John is not in phone directory.")