A loop is programming statement that cause a statement or set of statements to execute repeatedly. Most loops should have condition logic built into them that causes the loop to end. A loop that does not end is known as an "infinite loop". Looping statements are also sometimes referred to as repetition or iteration statements.
The two main types of loops are:
- Count-controlled loop, i.e. definite loop
- Repeats instructions a specific number of times
- Often performed with a for loop
- Condition-controlled loop, i.e. indefinite loop
- Repeats instructions while a condition is true
- Often performed with a while loop, do-while loop, or do-until loop
Python has both for and whie looop.
Another ways loops can be categorized is as a pre-test loop or post-test loop. Python only has pre-test loops, i.e. it doe snot haev a do ... while loop.
Example: For loop in Python
for x in range(1, 5):
print ("x=", x)
Output:
x= 1
x= 2
x= 3
x= 4
Example: For loop with accumulator in Python
total = 0
for x in range(4):
total = total + x
print("x=", x, "Total=", total)
Output:
x= 0 Total= 0
x= 1 Total= 1
x= 2 Total= 3
x= 3 Total= 6
Example: For loop in Python
max = int(input("Enter maximum number:"))
for i in range(1,max):
print("i =", i)
Output:
Enter maximum number: 4 {user input)
i = 1
i = 2
i = 3
Example: For loop in Python
for i in range(3,0,-1):
print (i)
Output:
3
2
1
Python has three loop control structures:
- break statement - terminates loop and transfers execution to statement immediately following loop.
- continue statement - causes loop to skip remainder of its body and retest condition prior to reiterating.
- pass statement - used when statement is required syntactically but you do not want any command or code to execute.
Example: For loop in Python
# Prints odd numbers between 0 and 7
for x in range(1, 8):
if x % 2 == 0:
continue
print (x)
Output:
1
3
5
7
Example: For loop in Python based on user input (n)
n = int(input('Enter maximum value: '))
for i in range(n):
if i % 2 == 0:
continue
print (i)
Example: Nested For loop in Python
for x in range(1, 4):
for y in range(1, 3):
print (x, '*', y, '=', x*y )
Output:
1 * 1 = 1
1 * 2 = 2
2 * 1 = 2
2 * 2 = 4
3 * 1 = 3
3 * 2 = 6
Example: For loop with list in Python
list = [5,10,20,30]
sum = 0
for num in list:
sum = sum + num
print ("The sum is: ", sum)
Output:
The sum is 65
Example: For loop with list in Python
fruits = ['oranges', 'pears', 'grapes', 'apples']
for fruit in fruits:
print ("I like %s" % fruit)
Output:
I like oranges
I like pears
I like grapes
I like apples
Example: For loop in Python
string = "Hello"
for x in string:
print (x)
Output:
H
e
l
l
o
Example: For loop in Python
# Loop will call function three times and display quote three times
def displayQuote():
print("The computer is incredibly fast, accurate, and stupid. \n"
"Man is unbelievably slow, inaccurate, and brilliant. \n"
"The marriage of the two is a force beyond calculation. \n"
"-Leo Cherne, attributed, The World of Work: Careers and the Future.\n")
for x in range(0,3):
displayQuote()
Example: For loop inside function in Python
def calcRaise(salary, perc):
total = 0
print("Current salary is: ", salary)
for x in range(1, 6):
salary = salary * (1 + perc)
print("Salary in the next year is $%.2f" % salary)
total = total + salary
return total
salary = float(input("Enter current salary: "))
perc = float(input("Enter annual raise amount: "))
total = calcRaise(salary, perc)
print("You will make a total of $%.2f over the next five years" % total)
Output:
Enter current salary: 50000
Enter annual raise amount: .04
Current salary is: 50000.0
Salary in the next year is $52000.00
Salary in the next year is $54080.00
Salary in the next year is $56243.20
Salary in the next year is $58492.93
Salary in the next year is $60832.65
You will make a total of $281648.77 over the next five years
Example: For loop with list and nested if statement in Python
at_home = ["oranges", "olives","bananas","pickles"]
for food in at_home:
if food == "anchovies":
print("No more anchovies please!")
break
print("Great. I really like " + food)
else:
print("Fantastic - no anchovies!")
print("I'm full now.")
Output:
Great. I really like oranges
Great. I really like olives
Great. I really like bananas
Great. I really like pickles
Fantastic - no anchovies!
I'm full now.
Example: For loop in Python - 99 bottles of water using decrement
for i in range(99, 0, -1):
if i == 1:
print('1 bottle of water on the wall, 1 bottle of water!')
print('Take it down, pass it around, no more bottles of water on the wall!')
else:
print('{0} bottles of water on the wall, {0} bottles of water!'.format(i))
print('Take one down, pass it around, {0} more bottles of water on the wall!'.format(i - 1))
Example: For loop inside function in Python with accumulator (total) and returning two variables
def loopFunction(total): # function returns two values
num = int(input("How many times do you want to loop? "))
for x in range(num):
total = total + x
print("x=", x)
return num, total
total = 0
print("Before loop: x=", x, "and total =", total)
x, total = loopFunction(total)
print("After loop: x=", x, "and total =", total)
Output:
Before loop: x= 3 and total = 0How many times do you want to loop? 4 {user input}
x= 0
x= 1
x= 2
x= 3
After loop: x= 4 and total = 6