Practical-3
Aim: Program to demonstrate looping statement
Python programming language provides two types of Python loopshecking time. In this
article, we will look at Python loops and understand their working with the help of examp
– For loop and While loop to handle looping requirements. Loops in Python provides
three ways for executing the loops.
While all the ways provide similar basic functionality, they differ in their syntax and
condition-checking time. In this article, we will look at Python loops and understand their
working with the help of examples.
Example of Python While Loop
Let’s see a simple example of a while loop in Python. The given Python code uses
a ‘while' loop to print “Hello Geek” three times by incrementing a variable
called ‘count' from 1 to 3.
Python
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Syntax of While Loop with else statement:
While condition:
# execute these statements
else:
# execute these statements
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
Hello Geek
Hello Geek
Hello Geek
In Else Block
Example with List, Tuple, String, and Dictionary Iteration Using for Loops in
Python
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)
print("\nDictionary Iteration")
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
print("\nSet Iteration")
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i),
Output
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Set Iteration
1
2
3
4
5
6