Professional Documents
Culture Documents
13 6 2024
13 6 2024
* * for i in range(1,6):
* * * for s in range(spaces):
* * * * print(" ",end=" ")
* * * * * for j in range(1,i+1):
print("* ",end=' ')
print()
spaces=spaces-1
* * * * * spaces=0
* * * * for i in range(5,0,-1):
* * * for s in range(spaces):
* * print(" ",end=" ")
* for j in range(1,i+1):
print("* ",end=' ')
print()
spaces=spaces+1
1 for i in range(1,6):
10 for j in range(1,i+1):
101 if j%2==0:
1010 print("0",end=' ')
10101 else:
print("1",end=' ')
print()
* for i in range(1,6):
*$ for j in range(1,i+1):
*$* if j%2==0:
*$*$ print("$",end=' ')
*$*$* else:
print("*",end=' ')
print()
Nested while
While loop inside while loop is called nested while.
num=1
while num<=10:
i=1
while i<=10:
p=num*i
print(f'{num}x{i}={p}')
i=i+1
num=num+1
Output
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5
1x6=6
1x7=7
1x8=8
1x9=9
1x10=10
2x1=2
2x2=4
2x3=6
2x4=8
2x5=10
2x6=12
2x7=14
2x8=16
2x9=18
2x10=20
# Write a program to generate factorials of numbers from 1 to 5
num=1
while num<=5:
fact=1
i=1
while i<=num:
fact=fact*i
i=i+1
Output
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
factorial of 5 is 120
Branching statements
1. break
2. continue
break
break is a keyword, which represents branching statement in python.
This statement is used inside while or for loop.
This statement is used to terminate execution of while loop or for
loop.
Example:
for i in range(1,11):
print("Hello")
break
i=1
while i<=10:
print("Bye")
i=i+1
break
Output
Hello
Bye
# Write a program to input numbers until user input -ve number
while True:
num=int(input("Enter any number"))
if num<0:
break
Output
Enter any number10
Enter any number20
Enter any number30
Enter any number-1
# Write a program to input username and password and until
username and password is valid
while True:
user=input("UserName :")
pwd=input("Password :")
if user=="nit" and pwd=="nit123":
print("welcome")
break
else:
print("invalid username or password try again...")
Output
UserName :abc
Password :xyz
invalid username or password try again...
UserName :nit
Password :naresh
invalid username or password try again...
UserName :nit
Password :nit123
Welcome
Example
# write a program to find input number is prime or not
if c==2:
print(f'{num} is prime')
else:
print(f'{num} is not prime')
Output
Enter any number 9
9 is not prime
continue
continue keyword represents branching statement in python.
This statement is used within while loop or for loop.
continue statement move the execution control from current line to
while or for statement.
Example:
for num in range(1,11):
if num%2==0:
continue
print(num)
Output
1
3
5
7
9
Example
for num in range(1,11):
continue
print(num)
Output
No output
Syntax-2:
while <condition>:
statement-1
statement-2
else:
statement-3
Syntax-2
for variable in iterable:
statement-1
statement-2
else:
statement-3