Loops allow programmers to run the same block of code repeatedly for a certain number of times.
While loops use conditional statements to determine the end of a loop.
x=0 while(x<=10): print(x*2)
num=int(input("Enter a positive integer number. Press 0 to stop")) while(num>0): print(num + 1) num=int(input("Enter a positive integer number. Press 0 to stop"))
This for loop works with a sequence of data items.
Each data item is assigned to the variable after each iteration (loop).
##Example 1 for num in [1,2,10,43,5]: print(num)
OUTPUT: 1 2 10 43 5
##Example 2 for class_name in ["Math", "English", "Science", "History"]: print("Course Name: "+class_name+" for Spring 2020") OUTPUT: Course Name: Math for Spring 2020 Course Name: English for Spring 2020 Course Name: Science for Spring 2020 Course Name: History for Spring 2020
In the example 1 above, the for loop uses the variable num to store each value in the list after each loop.
The loop will repeat 5 times because there are 5 items in the list
Example 2 demonstrates storing each string into the string variable class_name
and then running the
print statement for each time it runs the loop.
There are 5 class names in the list so, the loop will run 5 times.
range
is a built-in function in Python, which prints out lists of numbers.
This function is used in for loops to control how many times the loop repeats.
range(start,stop, step)
print(list(range(4))) #This line of code will output a list [0,1,2,3] excluding 4 print(list(range(1,4))) #This line of code will output a list [1,2,3] excluding 4
print(list(range(1,5))) #output: [1,2,3,4]
#Example 1 for num in range(10): print(str(num),end=" ") #output: 0 1 2 3 4 5 6 7 8 9 #Example 2 print("\n") #space for num in range (30,35): print(str(num),end=" ") #output: 30 31 32 33 34 #Example 3 print("\n") #space for num in range (20, 80, 20): print(str(num),end=" ") #output: 20 40 60 #Example 4 print("\n") #space for num in range (100, 50, -10): print(str(num),end=" ") #output: 100 90 80 70 60