For Loops
For Loops
Iterate through code like lists, tuple, dictionary:
lists, tuple, dictionary:# Itterate though a list
farm_animals = ['goat', 'horse', 'chicken', 'cow', 'dog']
# The 'animal' variable is defined in for loop:
for animal in farm_animals:
print(animal) # Will print each element in the list
sentence = animal + " is safe in our farm"
print(sentence) # Will print the sentence which each animal in list
print('hello world') # This will run as many times as items in the listIterating through string:
string:greeting = "hello my name is tim"
for char in greeting:
print(char) # prints each character separately
# End this look once we come accros the letter "N":
for char in greeting:
if char == "n":
break # If you want to move to next part of code but "break" out of the loop
print(char) The "break" argument is used to get out of a loop early and move on to the next part of the code that you are running
The "exit" argument is used to stop the code completely
The "continue" argument prevents the next lines of code in the loop to run but restarts the loop:
Last updated