Hi. Guys welcome back to another amazing tutorial on this platform. If you are new here, please check out our previous tutorial on python and subscribe to our YouTube channel for the video tutorials.
Today we are going to look at another interesting program on python called the python loops. To begin with, a loop is a control structure that allows the compiler to repeat the execution of a statement or group of statements. They are two main types of loops which are the ‘for loop’ and the ‘while loop’.
- The for loop
We can use the ‘for loop’ to execute programs which are in sequence data types such as lists, strings, or tuples.
Syntax
for val in sequence
statement(s)
The ‘for statement’ stores every value of each elements on the sequence until all the elements in the loop are exhausted. Let’s look at examples of for loop with data types
Loops with string
letter=('p','r','s','o','g','r')
for letter in 'programming':
print('<', letter, '>')
OUTPUT
For loop with a tuple
color=('red','green','balck')
for x in color:
print("I'm wearing a", x, "shirt")
print("multi-colored shirts are cool!")
OUTPUT
Using for loop with the range function
We can use the range function to know the exact numbers required by a loop.
x=15
total=0
for number in range(1, x+1):
total+=number
print("sum of 1 and numbers from 1 to %d:%d"%(x, total))
OUTPUT
The while loop
The “while loop” is used when you need to repeatedly execute a statement or group of statements while the given condition is true.
Syntax
While conditions
statements
Here is a program that adds number up to the desired number entered by the user.
i = 2
while i < 8:
print(i)
i += 1
OUTPUT
We used the break statement to end the present loop while instructing python to execute the first statement. It is commonly used to prevent the else statement.
Syntax
break
Here is a loop that ends once it reaches the word ‘sloth’
animals=['lion', 'tiger','sloth','elephant']
for name in animals:
if name=='sloth':
break
print('cool animal:', name)
print("Amazing animals!")
output
Continue statement
The compiler skips the specified iteration and takes all the other iterations.
Syntax
continue
Example
animals=['lion', 'tiger','elephant']
for name in animals:
if name=='sloth':
continue
print('cool animal:', name)
print("Amazing animals!")
OUTPUT
Pass statement
It is an empty operation in python. The interpreter reads and executes the pass statements but returns nothing as the result. It is mostly used to mark codes that will eventually be written.
Syntax
Pass
Comments
Post a Comment
Please do not enter any spam link in the comment box.