Loops
Loop is a repetitive process of an operation.
Python Provides 2 types of Loops
- for loop
- while loop
For loop
Syntax :
for variable in Sequence
- variable represents to an individual element of sequence
- sequence is nothing but a string, list, tuple or dictionary
# program to understand for loop
name = "Techno Xpresss"
for x in name:
print(x)
print("for loop completed")
#output
T
e
c
h
n
o
X
p
r
e
s
s
s
for loop completed
so here name is a sequence, which is string and x is a variable, picking up single character as an element and printing.
Every element is printed in next line, as by default print() ends with "\n" (new-line), but no worries, python provide developer to change the ending value of print()
# program to understand for loop
name = "Techno Xpresss"
for x in name:
print(x, end = "") # changing end to no action
print("\nfor loop completed")
#output
Techno Xpresss
for loop completed
# program to understand for loop
name = "Techno Xpresss"
for x in name:
print(x, end = " ") # changing end to space
print("\nfor loop completed")
#output
T e c h n o X p r e s s s
for loop completed
While Loop
Syntax :
while (condition is true)
# program to understand while loop
a=1
while (a != 11):
print(a)
a += 1
#output
1
2
3
4
5
6
7
8
9
10
# program to understand for loop
a=1
while (a != 11):
print(a, end = " ")
a += 1
#output
1 2 3 4 5 6 7 8 9 10
Comments
Post a Comment