#IF-ELSE Statements:
1) electricity bill calculation, units in rupees
//Code snippet
units_consumed=int(input("Enter the toatl units consumed: "))
bill=0
if(units_consumed<=100):
bill=units_consumed*200
elif(units_consumed>=101 and units_consumed<=200 ):
bill=100 * 200 + (units_consumed-100) * 300
elif(units_consumed>=201):
bill=200.50 + 200.60 + (units_consumed-200)*400
print("The total electricity bill consumed is: ",bill,"/-")
//input and output:
Enter the total units consumed: 4
The total electricity bill consumed is: 800 /-
2)menu driven calculator using branching:
//code snippet
def operation(a,b,char):
if(char==1):
return (a+b)
elif(char==2):
return a-b
elif(char==3):
return (b-a)
elif(char==4):
if(b==0):
return 0
else:
return (a/b)
elif(char==5):
if(a==0):
return 0
else:
return (b/a)
elif(char==6):
return (a%b)
elif(char==7):
return a*b
else: return "error"
option=1
while(option==1):
a=int(input("Enter the first Number: "))
b=int(input("Enter the Second Number: "))
print("------------------------------------------------------------
--")
print("[Link](+)\[Link](a-b)\[Link](b-
a)\[Link](a/b)\[Link](b/a)\[Link](a%b)\[Link](a
*b)")
char=int(input("Select your choice: "))
value=operation(a,b,char)
if(value=="error"):
print("Enter a valid operator")
elif(value==0):
print("Invalid Operation!!\nPlease Enter a valid Operation!!")
else:
print("The result is: ",value)
option=int(input("Do you want to continue(1--Yes||0--NO): "))
//Input and Output:
Enter the first Number: 5
Enter the Second Number: 8
------------------------------------------------------------
[Link](+)
[Link](a-b)
[Link](b-a)
[Link](a/b)
[Link](b/a)
[Link](a%b)
[Link](a*b)
Select your choice: 1
The result is: 13
Do you want to continue(1--Yes||0--NO): 0
==============================================================
3)login authentication and withdraw with multiple conditions:
//Code Snippet
from _Functions import counter
import time
def accountmenu():
Account_balance=3000
option=1
while(option):
print("[Link] Account Balance\[Link] Ammount\[Link]
Amount\[Link](e|E)")
choice=int(input("Enter your choice: "))
if(choice==1):
print("Balance in your Ammount is: ",Account_balance)
elif(choice==2):
with_amount=int(input("Enter the Amount to withdraw : "))
if(with_amount>Account_balance):
print("Insufficent Balance!!")
else:
Account_balance=Account_balance-with_amount
print("Current Balance is: ",Account_balance)
elif(choice==3):
cre_Amount=int(input("Enter the amount to Credit: "))
Account_balance+=cre_Amount
print("Current Balance is: ",Account_balance)
elif(choice==4):
print("Thank You for using our program!!")
return 0
print("Press 1 to back to menu\nPress 0 to close")
option=int(input())
if(option==0): break
return 0
def account_pin():
try:
with open("account_pin.txt",'r') as f:
acc_pin = int([Link]().strip())
except FileNotFoundError:
with open("account_pin.txt",'w') as f:
[Link]("3856")
acc_pin = 3856
for i in range(3):
attempts_left=None
pin = int(input("Enter your four digit pin: "))
if len(str(pin)) != 4:
print("Enter a valid 4-digit pin")
continue
if pin == acc_pin:
accountmenu()
break
else:
attempts_left = 2 - i
if(attempts_left==0):
print("Account locked for 1 minute!")
[Link](60)
break
print(f"Invalid! {attempts_left} attempts left!")
def account_num():
while True:
account_number=int(input("Enter your account Number: "))
if(not counter(account_number,12)):
print("INVALID Account Number!!Re-enter your Number")
continue
else:
with open('Account_details.txt','a') as f:
[Link](f"{str(account_number)}\n")
break
option=1
while(option):
print("------------Welcome to ATM System---------------------------
")
account_num()
account_pin()
option=int(input("do you want to want to exit(press 0|press 1 to
continue: "))
print("-----------------------------------------------------------")
//Input and Output:
Enter your account Number: 98746798368
INVALID Account Number!!Re-enter your Number
Enter your account Number: 346789467892
Enter your four digit pin: 7898
Invalid! 2 attempts left!
Enter your four digit pin: 3856
[Link] Account Balance
[Link] Amount
[Link] Amount
[Link](e|E)
Enter your choice: 1
Balance in your Amount is: 3000
Press 1 to back to menu
Press 0 to close
0
do you want to want to exit(press 0|press 1 to continue: 0
4) students result grading system:
a=int(input("Enter the number of Students: "))
MarksList=[]
for i in range(a):
print("Enter the marks of Student ",(i+1),": ",end="")
[Link](int(input()))
avg=0
for marks in MarksList:
avg=avg+marks
avg=avg/a
print("Class average is: ",avg)
b=0
print("Toppers are:-")
for i in range(a):
if(avg<MarksList[i]):
b+=1
print("Topper ",b," :- ","Student ",(i+1)," :",MarksList[i])
if(b==0):
print("No Student got above class Average..!!")
//Input and Output:
Enter the number of Students: 5
Enter the marks of Student 1 : 98
Enter the marks of Student 2 : 67
Enter the marks of Student 3 : 56
Enter the marks of Student 4 : 88
Enter the marks of Student 5 : 76
Class average is: 77.0
Toppers are:-
Topper 1 :- Student 1 : 98
Topper 2 :- Student 4 : 88
5) leap year checker :
//Code Snippet:
def leap_Checker(n):
return ((n%400==0) or (n%4==0 and n%100!=0))
year=int(input("Enter a Year: "))
if(leap_Checker(year)):
print(f"{year} is a leap Year!")
else:
print(f"{year} is not a leap Year!")
//Input and Output:
Enter a Year: 2097
2097 is not a leap Year!
6) ticket pricing based on age:
def ticket_checker(age,adult_price):
if age < 5:
price = 0
category = "Free (Baby)"
elif age>=5 and age<=12:
price = adult_price * 0.5
category = "Child"
elif age>=13 and age<=17:
price = adult_price * 0.75
category = "Student/Teen"
elif(age>=18 and age<=59):
price = adult_price
category = "Adult"
else:
price = adult_price * 0.5 # ₹100
category = "Senior"
return price,category
print("=== AGE-BASED TICKET PRICING ===")
adult_price = 200
age = int(input("Enter age: "))
price,category=ticket_checker(age,adult_price)
print(f"Your category: {category}")
print(f"Ticket price: {price:.0f}/-")
//Input and Output:
=== AGE-BASED TICKET PRICING ===
Enter age: 56
Your category: Adult
Ticket price: 200/-
7) loan eligibility system :
//Code Snippet
def
isEligible(eligible,reasons,credit_score,monthly_debt,monthly_income,jo
b_years):
if age < 21 or age > 60:
eligible = False
[Link]("Age must be 21-60")
if monthly_income < 25000:
eligible = False
[Link]("Income >= ₹25,000")
if credit_score < 750:
eligible = False
[Link]("Credit score >= 750")
if (monthly_debt / monthly_income) > 0.5:
eligible = False
[Link]("Debt ratio <= 50%")
if job_years < 1:
eligible = False
[Link]("Job stability >= 1 year")
return reasons,eligible
name = input("Enter your name: ")
age = int(input("Enter age: "))
monthly_income = float(input("Monthly income (₹): "))
credit_score = int(input("Credit score (300-900): "))
monthly_debt = float(input("Monthly debt/EMI (₹): "))
job_years = float(input("Years in current job: "))
eligible = True
reasons = []
reasons,eligible=isEligible(eligible,reasons,credit_score,monthly_debt,
monthly_income,job_years)
max_loan = int((monthly_income - monthly_debt) * 55)
print("==========Results==============")
if(eligible):
print(f"{name}, you are ELIGIBLE!")
print(f"Max loan amount: ₹{max_loan:,}")
else:
print(f"{name}, not eligible.")
print("Reasons:", ", ".join(reasons))
print("Improve and try again!")
//Input and Output:
Enter your name: Surya
Enter age: 34
Monthly income (₹): 26000
Credit score (300-900): 400
Monthly debt/EMI (₹): 7000
Years in current job: 2
==========Results==============
Surya, not eligible.
Reasons: Credit score >= 750
Improve and try again!
8) quadratic equations roots classification :
//Code Snippet:
import cmath
import math
def _Calculate(a,b,c):
D=(b*b)-(4*a*c)
if(D<0):
print("The roots are imaginary!")
_pos_root=((-b)+ [Link](D))/2*a
_neg_root=((-b)- [Link](D))/2*a
_+=23
else:
print("Roots are real!!")
_pos_root=((-b)+ [Link](D))/2*a
_neg_root=((-b)- [Link](D))/2*a
# roots=[_pos_root,_neg_root]
# return roots
return _pos_root,_neg_root
print("Enter the coeffients of the Quadratic equation of the form
ax^2+bx+c=0 :")
a=int(input("a= "))
b=int(input("b= "))
c=int(input("c= "))
root1,root2=_Calculate(a,b,c)
print(f"Root 1: {root1} and ,Root 2: {root2}")
//Input and Output:
Enter the coeffients of the Quadratic equation of the form
ax^2+bx+c=0 :
a= 1
b= -2
c= 1
Roots are real!!
Root 1: 1.0 and ,Root 2: 1.0
9) traffic signal simulator :
//Code Snippet:
import time
while(True):
print("Red Light!!Stop where you are!! and Wait for 20 secs")
time.perf_counter()
[Link](20)
print("---------------------------------------------------")
print("Yellow!!Get ready and be patient for 10 secs")
[Link](10)
print("====================================================")
print("Green!!You are good to go now!!")
print("Always follow traffic Rules!!")
print("Reach your path within 20 secs")
[Link](20)
print("--------------------------------------------------------")
//Input and Output:
Red Light!!Stop where you are!! and Wait for 20 secs
-----------------------------------------------
Yellow!!Get ready and be patient for 10 secs
================================================
Green!!You are good to go now!!
Always follow traffic Rules!!
Reach your path within 20 secs
#Loop Statements:
1) Write a Python program to convert a given decimal number into
its binary equivalent.
//Code Snippet:
def check(val):
if(val==10):
return 'A'
elif(val==11):
return 'B'
elif(val==12):
return 'C'
elif(val==13):
return 'D'
elif(val==14):
return 'E'
elif(val==15):
return 'F'
else:
return val
def convert_hex(n):
remin=n%16
rem=check(remin)
if((n==0)):
print(rem,end="")
return
a=int(n/16)
convert_hex(a)
print(rem,end="")
return
def convert_(n,m):
remin=n%m
if((n==0)):
print("result is: ",end='')
print(remin,end="")
return
a=int(n/m)
convert_(a,m)
print(remin,end="")
return
while(True):
n=int(input("Enter the number: "))
b=int(input("Enter the base: "))
if(b==16):
convert_hex(n)
print()
continue
convert_(n,b)
print()
#USE bin(number)---returns a binary
//Input and Output:
Enter the number: 64
Enter the base: 2
result is: 01000000
2) Write a Python program to find the Greatest Common Divisor
(GCD) of two given numbers.
//Code Snippet:
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
_gcd = gcd(a, b)
print(f"GCD: {_gcd}")
//INPUT AND OUTPUT:
Enter 1st number: 20
Enter 2nd number: 6
GCD: 2
3) Write a Python program to print all the prime numbers from the
given set of numbers.
//Code Snippet:
import math
def prime_Check(n):
count=0
for i in range(2,([Link](n)+1)):
if(n%i==0):
count+=1
return count
def prime_Display(n):
for i in range(2,n+1):
if(not prime_Check(i)):
print(i,end=" ")
print("")
while(True):
n=int(input("Enter the range of Prime: "))
prime_Display(n)
//INPUT AND OUTPUT:
Enter the range of Prime: 500
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113 127 131 137 139 149
151 157 163 167 173 179 181 191 193 197 199 211 223
227 229 233 239 241 251 257 263 269 271 277 281 283
293 307 311 313 317 331 337 347 349 353 359 367 373
379 383 389 397 401 409 419 421 431 433 439 443 449
457 461 463 467 479 487 491 499
4) Write a Python program to print number patterns using nested-
for loop.
//Code Snippet:
for i in range(1,6):
for j in range(1,5):
print(" ", end="")
for j in range(1,(2*i-1)+1):
if j==1 or j==(2*i-1) or i==5:
print("*", end=" ")
else:
print(" ", end=" ")
print(" ")
#------------------------------------------------
for i in range(1,6):
for j in range(1,i+1):
print(j,end=" ")
print(" ")
#-----------------------
n = int(input())
for i in range(1, n + 1):
# spaces
for j in range(n - i):
print(" ", end="")
# stars
for j in range(i):
print(" * ", end=" ")
print()
//INPUT AND OUTPUT:
Enter a Number: 5
*
* *
* *
* *
* * * ** * * **
Enter a number: 5
1
1 2
1 2 3
1 2 34
1 2 34 5
Enter a number : 5
*
* *
* * *
* * * *
* * * * *
5) Write a Python program to check whether a given number is:
o Perfect
o Strong
o Armstrong
//Perfect Number:
def divisor_check(n):
sum=0
for i in range(1,n):
if(n%i==0):
sum+=i
else: continue
return n==sum
def multiple_display(n):
for i in range(1,n):
if(n%i==0):
print(i,end=" ")
else: continue
n=int(input("Enter a number: "))
if(divisor_check(n)):
print("It is A Perfect Number")
else:
print("Not a perfect Number")
print("factors are: ",end="")
multiple_display(n)
//INPUT AND OUTPUT:
Enter a number: 6
It is A Perfect Number
factors are: 1 2 3
//Strong Number:
def factorial(n):
if(n==1 or n==0):
return 1
return n*factorial(n-1)
def sum_of_fac(n):
if(n==0):
return 0
fact=factorial(n%10)
return fact+sum_of_fac(int(n/10))
n=int(input("Enter a Number: "))
fact_value=sum_of_fac(n)
print("Sum of factorial of the digits of the given number
is:",fact_value)
if(fact_value==n):
print("STrong NUMBER!!")
else:
print("NOT a strong NUMBER!!")
//INPUT AND OUTPUT:
Enter a Number: 145
Sum of factorial of the digits of the given number is: 145
STrong NUMBER!!
//Amstrong Number:
def count(n):
count=0
while(n>=1):
count+=1
n=int(n/10)
return count
def amstrong_num(n):
digits=count(n)
sum=0
while(n>=1):
a=n%10
sum+=(a**digits)
n=int(n/10)
return sum
n=int(input("Enter a Number: "))
if(amstrong_num(n)==n):
print("It is an Amstrong Number!!")
else:
print("Not an Amstrong Number!!")
//INPUT AND OUTPUT:
Enter a Number: 46
Not an Amstrong Number!!
#/Because (4^2+6^2)!=46
6) To find the sum of squares of first n natural numbers.
//Code Snippet:
#1+2^2+3^2+.............till n
def series_sum(n):
if(n==0 or n==1):
return n
a=n**2
return a+series_sum(n-1)
n=int(input("Enter the sum of series till : "))
print(f"Sum of series till {n} is : {series_sum(n)}")
//INPUT AND OUTPUT:
Enter the sum of series till : 10
Sum of series till 10 is : 385
#(1^2+2^2+3^2+4^2+5^2+6^2+7^2+8^2+9^2+10^2)
7) To generate Fibonacci series up to n terms.
//Code Snippet:
def fibb(n):
if(n==1 or n==0):
return n
return fibb(n-1)+fibb(n-2)
n=int(input("Enter the length: "))
print("Series: ",end="")
for i in range(n):
print(fibb(i)," ",end="")
//INPUT AND OUTPUT:
Enter the length: 15
Series: 0 1 1 2 3 5 8 13 21 34 55 89 144
233 377
8) To check whether a given number is a palindrome.
//Code Snippet:
def reverse_check(n):
sum=0
while(n>=1):
a=n%10
sum=int(sum*10+a)
n=int(n/10)
return sum
n=int(input("Enter the number: "))
if(reverse_check(n)==n):
print("Number is Palindrome")
else:
print("Number is not a Palindrome")
//INPUT AND OUTPUT:
Enter the number: 456654
Number is Palindrome
9) To reverse a given number using loops.
//Code Snippet:
n=int(input("Enter the number: "))
sum=0
while(n>=1):
a=n%10
sum=int(sum*10+a)
n=n/10
print("Reversed number is:",sum)
//INPUT AND OUTPUT:
Enter the number: 2345
Reversed number is: 5432
10) Write a Python program to find the Least Common Multiple (LCM) of
two given numbers.
//Code Snippet:
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return int((a * b) / gcd(a, b) )
a = int(input("Enter 1st number: "))
b = int(input("Enter 2nd number: "))
result = lcm(a, b)
print(f"LCM of {a} and {b}: {result}")
//Input and Output:
Enter 1st number: 20
Enter 2nd number: 6
LCM of 20 and 6: 60