Basic Programs
Simple Calculator (Addition, Subtraction, Multiplication, Division)
def calculator(a, b, op):
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
else:
return "Invalid Operator"
print(calculator(10, 5, '+'))
Swap Two Numbers Without Using a Third Variable
a, b = 10, 20
a = a + b
b = a - b
a = a - b
print("a =", a, "b =", b)
Find the Largest of Three Numbers
a, b, c = 10, 20, 15
largest = max(a, b, c)
print("Largest number is:", largest)
Check if a Number is Even or Odd
num = 7
print("Even" if num % 2 == 0 else "Odd")
Calculate the Factorial of a Number
num = 5
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)
Generate Fibonacci Series
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
Reverse a Number
num = 1234
rev = 0
while num != 0:
rev = rev * 10 + num % 10
num //= 10
print("Reversed Number:", rev)
Check if a Number is Palindrome
num = 121
rev = int(str(num)[::-1])
print("Palindrome" if num == rev else "Not Palindrome")
Check if a Number is Positive, Negative, or Zero
num = -5
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Check if a Year is a Leap Year
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap Year")
else:
print("Not a Leap Year")
Print Even Numbers from 1 to N using for loop
n = 20
for i in range(1, n+1):
if i % 2 == 0:
print(i, end=' ')
Print Multiplication Table of a Given Number using while loop
num = 5
i = 1
while i <= 10:
print(f"{num} x {i} = {num*i}")
i += 1
Calculate the Sum of Digits of a Number using while loop
num = 1234
sum_digits = 0
while num != 0:
sum_digits += num % 10
num //= 10
print("Sum of digits:", sum_digits)
Check if a Number is Armstrong or Not using while loop
num = 153
temp = num
sum_arm = 0
while temp != 0:
digit = temp % 10
sum_arm += digit ** 3
temp //= 10
print("Armstrong Number" if sum_arm == num else "Not Armstrong")
Simple Menu-Driven (Restaurant) Program using switch-case (Using if-elif-else in Python)
print("1. Burger\n2. Pizza\n3. Cold Drink")
choice = int(input("Enter your choice: "))
if choice == 1:
print("You ordered Burger.")
elif choice == 2:
print("You ordered Pizza.")
elif choice == 3:
print("You ordered Cold Drink.")
else:
print("Invalid choice.")