#12 Python :- Infinite loop, For loop , Pass, Continue and Break Keywords
Infinite loop:
It is the loop which never stops until we stop it.
e.q. while True:
print("Gurpreet") ------> It prints Gurpreet infinite times.
Note:- Sometimes infinite loop started by mistake and sometimes we need to start it.
For loop:-
We can use this loop in place of while loop.
e.q. print Gurpreet 5 times.
Code:- # for loop with range function (start,stop, step arguments)
for i in range(5): # 0 to 4
print(f"Gurpreet : {i}")
Output:- Gurpreet : 0
Gurpreet : 1
Gurpreet : 2
Gurpreet : 3
Gurpreet : 4
Q1:- Sum of numbers from zero to 10.
Code:-
sum=0
for i in range(11):
sum+=i
print(sum)
Output:- 55
Q2:- Take any number as input and sum their digit. e.q. if you take 123=1+2+3=6.
num= input("Enter the number")
length=len(num)
total=0
for i in range(0,length):
total=total+int(num[i])
print(total)
Q3:- Take any name from user as input and print the frequency of each number.
name= input("Enter your name:- ")
for i in range(0,len(name)):
if name[i] not in name[0:i]:
print(f"{name[i]}:{name.count(name[i])}")
Output:-
Enter your name:- Gurpreet Singh
G:1
u:1
r:2
p:1
e:2
t:1
:1
S:1
i:1
n:1
g:1
h:1
For loop in list:-
e.q. fruits = ['banana', 'mango', 'grapes', 'kiwi']
for i in fruits:
print(i)
Output:- banana
mango
grapes
kiwi
Pass keyword:-
It is used to simple to pass the next step without printing anything.
for i in range(1,7):
if i==5:
pass
print(i)
Output:- #here it passes the next step when some condition became true.
2
3
4
5
6
Break Keyword:-
It is used to break the statement when some condition became true.
e.q.
for i in range(1,7):
if i==5:
break
print(i)
Output:- #here loops breaks when condition is fulfilled
1
2
3
4
Continue Keyword:-
It is used in place where you want to skip print statement upon some conditions.
for i in range(1,7):
if i==5:
continue
print(i)
Output:- #here is just skip the print statement only when condition became true.
1
2
3
4
6
Note:- The above way is universal which works in all languages.
Let us look at much more simple way of doing above problems using python :-
Sol 2:-
num = input("Enter any number:- ")
total =0
for i in num:
total +=int(i)
print(total)
Comments
Post a Comment