Skip to main content

Python Programs

Program to take user's name as input and display a welcome message

# Taking input from the user
name = input("Enter your name: ")
# Displaying message
print("Hi", name + ", welcome to Python programming class")

Variable program in Python

# Assigning values to variables
name = "Saubhagya"
age = 21
height= 5.10

# Displaying the values
print("Name:", name)
print("Age:", age)
print("height:", height)

# Using string concatenation
print("Hi  " + name + ", you are " + str(age) + " years old and your height is " + str(height)+ ".")

Program to demonstrate Dynamic Typing in Python

# Variable initially holds an integer
x = 10
print("Value of x:", x, "| Type of x:", type(x))

# Now assign a string to the same variable
x = "Hello"
print("Value of x:", x, "| Type of x:", type(x))

# Now assign a float to the same variable
x = 3.14
print("Value of x:", x, "| Type of x:", type(x))

# Now assign a boolean to the same variable
x = True
print("Value of x:", x, "| Type of x:", type(x))

Python program using input and output.

# Taking input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Producing output
print(f"Hello {name}, you are {age} years old.")
print("Hello{}, you are{} years old.".format(name, age))
#Old-style formatting
print("Hello %s, you are %d years old." % (name, age))

Program to demonstrate Numeric Data Types and Methods in Python

import math   # for mathematical functions
import cmath  # for complex number functions

# Integer
a = 25
print("a =", a, "| Type:", type(a))
print("Absolute value of a:", abs(a))
print("Binary of a:", bin(a))
print("Octal of a:", oct(a))
print("Hexadecimal of a:", hex(a))

print("-" * 40)

# Float
b = -7.5
print("b =", b, "| Type:", type(b))
print("Absolute value of b:", abs(b))
print("Rounded value of b:", round(b))
print("Ceil of b:", math.ceil(b))
print("Floor of b:", math.floor(b))
print("Square root of 16:", math.sqrt(16))

print("-" * 40)

# Complex
c = 3 + 4j
print("c =", c, "| Type:", type(c))
print("Real part:", c.real)
print("Imaginary part:", c.imag)
print("Conjugate of c:", c.conjugate())
print("Magnitude of c:", abs(c))
print("Phase of c:", cmath.phase(c))

print("-" * 40)

# Type Conversion
x = 10.75
print("x =", x, "| Type:", type(x))
print("Convert float to int:", int(x))
print("Convert int to float:", float(a))
print("Convert int to complex:", complex(a))

Program to demonstrate Boolean Data Type in Python

# Boolean variables
a = True
b = False

print("a =", a, "| Type:", type(a))
print("b =", b, "| Type:", type(b))

Program to demonstrate String Data Type in Python

# Creating strings
str1 = "Hello"
str2 = 'Saubhagya'
str3 = """Welcome to the
1st  
Python Programming Class"""

print("str1 =", str1, "| Type:", type(str1))
print("str2 =", str2, "| Type:", type(str2))
print("str3 =", str3, "| Type:", type(str3))

print("-" * 50)

# String concatenation
full_str = str1 + " " + str2
print("Concatenation:", full_str)

# String repetition
repeat_str = str1 * 3
print("Repetition:", repeat_str)

# Accessing characters
print("First character of str2:", str2[0])
print("Last character of str2:", str2[-1])

# String slicing
print("First 3 characters of str2:", str2[:3])
print("Characters from index 1 to 4 of str2:", str2[1:7:2])

print("-" * 50)

# String methods
sample = "  python programming  "
print("Original String:", sample)
print("Uppercase:", sample.upper())
print("Lowercase:", sample.lower())
print("Title Case:", sample.title())
print("Strip spaces:", sample.strip())
print("Replace 'python' with 'Java':", sample.replace("python", "Java"))
print("Split into words:", sample.split())
print("Does string start with 'py'? :", sample.strip().startswith("py"))
print("Does string end with 'ing'? :", sample.strip().endswith("ing"))
print("Count of 'm':", sample.count("m"))
print("Length of sample:", len(sample))

Program to demonstrate List Data Type and Methods in Python

# Creating lists
fruits = ["apple", "banana", "cherry", "apple"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "hello", 3.14, True]

print("Fruits List:", fruits)
print("Numbers List:", numbers)
print("Mixed List:", mixed)

print("-" * 50)

# Accessing elements
print("First fruit:", fruits[0])
print("Last number:", numbers[-1])
print("Slice fruits[1:3]:", fruits[1:3])

print("-" * 50)

# Adding elements
fruits.append("orange")          # add at end
print("After append:", fruits)

fruits.insert(1, "grape")        # insert at index
print("After insert:", fruits)

fruits.extend(["mango", "kiwi"]) # add multiple
print("After extend:", fruits)

print("-" * 50)

# Removing elements
fruits.remove("apple")           # remove first occurrence
print("After remove 'apple':", fruits)

popped = fruits.pop()            # remove last element
print("Popped element:", popped)
print("After pop:", fruits)

popped_index = fruits.pop(2)     # remove by index
print("Popped element at index 2:", popped_index)
print("After pop at index 2:", fruits)

del fruits[0]                    # delete element at index
print("After del fruits[0]:", fruits)

fruits.clear()                   # remove all elements
print("After clear:", fruits)

print("-" * 50)

# Recreating fruits list
fruits = ["apple", "banana", "cherry", "apple"]

# Searching elements
print("Index of 'banana':", fruits.index("banana"))
print("Count of 'apple':", fruits.count("apple"))

print("-" * 50)

# Sorting and Reversing
numbers = [50, 10, 30, 40, 20]
print("Original numbers:", numbers)

numbers.sort()
print("Sorted ascending:", numbers)

numbers.sort(reverse=True)
print("Sorted descending:", numbers)

numbers.reverse()
print("After reverse:", numbers)

print("-" * 50)

# Copying lists
copy_list = numbers.copy()
print("Copied list:", copy_list)

# Using list() constructor
new_list = list(("x", "y", "z"))
print("New list from constructor:", new_list)

print("-" * 50)

# Looping through list
print("Looping through numbers:")
for n in numbers:
    print(n, end=" ")

print("\n" + "-" * 50)

# List comprehension
squares = [x**2 for x in range(1, 6)]
print("Squares using list comprehension:", squares)

# Filtering using list comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
print("Even numbers from numbers list:", even_numbers)

print("-" * 50)

# Nested lists
nested = [[1, 2], [3, 4], [5, 6]]
print("Nested list:", nested)
print("Access nested element [1][0]:", nested[1][0])

Program to demonstrate Tuple Data Type in Python

# Creating tuples
cars = ("BMW", "Audi", "Tesla", "Toyota", "Honda", "BMW")
print("Cars Tuple:", cars)
print("Type of cars:", type(cars))

print("-" * 50)

# Accessing elements
print("First car:", cars[0])
print("Last car:", cars[-1])
print("Slice cars[1:4]:", cars[1:4])

print("-" * 50)

# Searching in tuple
print("Index of Tesla:", cars.index("Tesla"))
print("Count of BMW:", cars.count("BMW"))

print("-" * 50)

# Looping through tuple
print("Looping through cars:")
for car in cars:
    print(car)

print("-" * 50)

# Tuple length
print("Number of cars:", len(cars))

print("-" * 50)

# Membership test
print("Is 'Audi' in cars?", "Audi" in cars)
print("Is 'Ford' not in cars?", "Ford" not in cars)

print("-" * 50)

# Nesting tuples
brands = ("Ford", "Chevrolet")
all_cars = (cars, brands)
print("Nested Tuple:", all_cars)
print("Access nested element [1][0]:", all_cars[1][0])

print("-" * 50)

# Tuple concatenation
more_cars = ("Jaguar", "Lamborghini")
new_tuple = cars + more_cars
print("After concatenation:", new_tuple)

# Tuple repetition
repeat_tuple = ("BMW",) * 3
print("Repeated tuple:", repeat_tuple)

print("-" * 50)

# Converting tuple to list (to modify)
car_list = list(cars)
car_list.append("Mercedes")  # add new car
car_list.remove("Tesla")     # remove a car
print("Modified car list:", car_list)

# Converting back to tuple
cars = tuple(car_list)
print("Modified cars tuple:", cars)

print("-" * 50)

# Unpacking tuple
car1, car2, car3, car4, car5, car6 = ("BMW", "Audi", "Tesla", "Toyota", "Honda", "Ford")
print("Unpacked values:")
print("Car1:", car1)
print("Car2:", car2)
print("Car3:", car3)
print("Car4:", car4)
print("Car5:", car5)
print("Car6:", car6)

print("-" * 50)

# Tuple with one element
single = ("BMW",)
print("Single element tuple:", single, "| Type:", type(single))

not_tuple = ("BMW")  # without comma, it's just a string
print("Without comma:", not_tuple, "| Type:", type(not_tuple))

Program to demonstrate Dictionary Data Type in Python

# Creating dictionary
car = {
    "brand": "Tesla",
    "model": "Model S",
    "year": 2022,
    "color": "Red"
}
print("Car Dictionary:", car)
print("Type of car:", type(car))

print("-" * 50)

# Accessing items
print("Brand:", car["brand"])
print("Model:", car.get("model"))   # safer way

print("-" * 50)

# Changing values
car["year"] = 2023
car["color"] = "Black"
print("After update:", car)

print("-" * 50)

# Adding items
car["price"] = 80000
print("After adding price:", car)

print("-" * 50)

# Removing items
car.pop("color")             # remove key
print("After pop color:", car)

removed = car.popitem()      # remove last key-value
print("Popped item:", removed)
print("After popitem:", car)

del car["model"]             # delete specific key
print("After del model:", car)

car.clear()                  # remove all items
print("After clear:", car)

print("-" * 50)

# Re-create dictionary
car = {
    "brand": "BMW",
    "model": "X5",
    "year": 2021
}

# Dictionary methods
print("Keys:", car.keys())
print("Values:", car.values())
print("Items:", car.items())

print("-" * 50)

# Looping through dictionary
print("Looping through keys:")
for key in car.keys():
    print(key)

print("Looping through values:")
for value in car.values():
    print(value)

print("Looping through key-value pairs:")
for key, value in car.items():
    print(key, ":", value)

print("-" * 50)

# Copy dictionary
new_car = car.copy()
print("Copied dictionary:", new_car)

# Using dict() constructor
another_car = dict(brand="Audi", model="Q7", year=2020)
print("Created with dict():", another_car)

print("-" * 50)

# Nested dictionary
garage = {
    "car1": {"brand": "Ford", "model": "Mustang", "year": 1967},
    "car2": {"brand": "Tesla", "model": "Model 3", "year": 2023},
    "car3": {"brand": "Toyota", "model": "Corolla", "year": 2019}
}
print("Garage Dictionary:", garage)
print("Access car2 model:", garage["car2"]["model"])

print("-" * 50)

# Setdefault() method
car = {"brand": "Jaguar"}
car.setdefault("color", "White")   # adds key if not present
print("After setdefault:", car)

print("-" * 50)

# Update() method (merge dictionaries)
car.update({"model": "F-Pace", "year": 2024})
print("After update:", car)

print("-" * 50)

# Fromkeys() method
keys = ["brand", "model", "year"]
default_car = dict.fromkeys(keys, "Unknown")
print("Dictionary from keys:", default_car)

Program to demonstrate Set Data Type and its methods

# Creating a set
cars = {"Tesla", "BMW", "Audi", "Ford"}
print("Original Set:", cars)
print("Type:", type(cars))

print("-" * 50)

# Adding elements
cars.add("Jaguar")
print("After add:", cars)

# Update set with multiple elements
cars.update(["Mercedes", "Toyota"])
print("After update:", cars)

print("-" * 50)

# Removing elements
cars.remove("Ford")    # Removes element, error if not present
print("After remove Ford:", cars)

cars.discard("Lamborghini")  # No error if not found
print("After discard Lamborghini (not present):", cars)

popped = cars.pop()   # Removes a random element
print("Popped element:", popped)
print("After pop:", cars)

cars.clear()          # Remove all elements
print("After clear:", cars)

print("-" * 50)

# Re-create sets for operations
set1 = {"Tesla", "BMW", "Audi", "Toyota"}
set2 = {"BMW", "Mercedes", "Audi", "Jaguar"}

# Union
print("Union:", set1.union(set2))
print("Union (|):", set1 | set2)

# Intersection
print("Intersection:", set1.intersection(set2))
print("Intersection (&):", set1 & set2)

# Difference
print("Difference (set1 - set2):", set1.difference(set2))
print("Difference (set2 - set1):", set2 - set1)

# Symmetric Difference
print("Symmetric Difference:", set1.symmetric_difference(set2))
print("Symmetric Difference (^):", set1 ^ set2)

print("-" * 50)

# Subset, Superset, Disjoint
setA = {"Audi", "BMW"}
setB = {"Audi", "BMW", "Tesla", "Toyota"}

print("setA is subset of setB?", setA.issubset(setB))
print("setB is superset of setA?", setB.issuperset(setA))
print("set1 and set2 are disjoint?", set1.isdisjoint({"Hyundai", "Kia"}))

print("-" * 50)

# Copy set
set_copy = set1.copy()
print("Copied set:", set_copy)

# Frozenset (immutable set)
frozen = frozenset(["Volvo", "Mini", "Kia"])
print("Frozenset:", frozen)

print("-" * 50)

# Using set() constructor
numbers = set([1, 2, 2, 3, 4, 4, 5])  # duplicates removed
print("Numbers set:", numbers)

Program to demonstrate Arithmetic Operators in Python

# Taking input
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))

print("\nArithmetic Operations:")
print("-" * 40)
print("Addition (a + b):", a + b)
print("Subtraction (a - b):", a - b)
print("Multiplication (a * b):", a * b)
print("Division (a / b):", a / b)
print("Floor Division (a // b):", a // b)
print("Modulus (a % b):", a % b)
print("Exponentiation (a ** b):", a ** b)

Program to demonstrate Relational Operators in Python

# Taking input
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))

print("\nRelational Operations:")
print("-" * 40)
print("a == b :", a == b)
print("a != b :", a != b)
print("a > b  :", a > b)
print("a < b  :", a < b)
print("a >= b :", a >= b)
print("a <= b :", a <= b)

Program to demonstrate Assignment Operators in Python

# Assigning value
a = int(input("Enter a number: "))
print("\nInitial value of a:", a)

print("-" * 40)

# Simple assignment
b = a
print("Assignment (=): b =", b)
a += 5
print("Add and assign (a += 5):", a)
a -= 3
print("Subtract and assign (a -= 3):", a)
a *= 2
print("Multiply and assign (a *= 2):", a)
a /= 4
print("Divide and assign (a /= 4):", a)
a //= 2
print("Floor divide and assign (a //= 2):", a)
a %= 3
print("Modulus and assign (a %= 3):", a)
a **= 4
print("Exponent and assign (a **= 4):", a)

Program to demonstrate Logical Operators in Python

# Taking input
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))

print("\nLogical Operations:")
print("-" * 40)
print("a > 5 and b > 5 :", a > 5 and b > 5)
print("a > 5 or b > 5  :", a > 5 or b > 5)
print("not(a > 5)      :", not (a > 5))
print("not(b > 5)      :", not (b > 5))

Program to demonstrate Bitwise Operators in Python

# Taking input
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))

print("\nBitwise Operations:")
print("-" * 50)
print("a & b  =", a & b, "   (Binary:", bin(a & b), ")")
print("a | b  =", a | b, "   (Binary:", bin(a | b), ")")
print("a ^ b  =", a ^ b, "   (Binary:", bin(a ^ b), ")")
print("~a     =", ~a, "   (Binary:", bin(~a), ")")
print("~b     =", ~b, "   (Binary:", bin(~b), ")")
print("a << 1 =", a << 1, "   (Binary:", bin(a << 1), ")")
print("a >> 1 =", a >> 1, "   (Binary:", bin(a >> 1), ")")

Program to demonstrate Membership Operators in Python

# String example
text = "Python Programming"

print("\nString Membership:")
print("-" * 40)
print("'Python' in text       :", "Python" in text)
print("'Java' in text         :", "Java" in text)
print("'Coding' not in text   :", "Coding" not in text)

# List example
numbers = [10, 20, 30, 40, 50]

print("\nList Membership:")
print("-" * 40)
print("20 in numbers          :", 20 in numbers)
print("60 in numbers          :", 60 in numbers)
print("70 not in numbers      :", 70 not in numbers)

# Tuple example
fruits = ("apple", "banana", "mango")

print("\nTuple Membership:")
print("-" * 40)
print("'apple' in fruits      :", "apple" in fruits)
print("'grapes' not in fruits :", "grapes" not in fruits)

# Set example
colors = {"red", "green", "blue"}

print("\nSet Membership:")
print("-" * 40)
print("'red' in colors        :", "red" in colors)
print("'yellow' in colors     :", "yellow" in colors)

# Dictionary example (membership works on KEYS only)
student = {"id": 101, "name": "Rahul", "course": "Python"}

print("\nDictionary Membership:")
print("-" * 40)
print("'id' in student        :", "id" in student)
print("'age' not in student   :", "age" not in student)
print("'Rahul' in student     :", "Rahul" in student)   # False because values are not checked by default

Program to demonstrate Identity Operators in Python

print("\nIdentity Operators Example")
print("-" * 50)

# Case 1: Numbers (small integers are cached in Python)
a = 10
b = 10
c = 20

print("a =", a, ", b =", b, ", c =", c)
print("a is b        :", a is b)        # True (same memory location, cached)
print("a is c        :", a is c)        # False
print("a is not c    :", a is not c)    # True

# Case 2: Strings (short strings may be cached)
x = "Python"
y = "Python"
z = "Java"

print("\nStrings:")
print("x =", x, ", y =", y, ", z =", z)
print("x is y        :", x is y)        # True (string interning)
print("x is z        :", x is z)        # False
print("x is not z    :", x is not z)    # True

# Case 3: Lists (mutable objects → different memory locations)
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1  # Both refer to the same list

print("\nLists:")
print("list1 =", list1)
print("list2 =", list2)
print("list3 =", list3)

print("list1 is list2 :", list1 is list2)   # False (different memory locations)
print("list1 is list3 :", list1 is list3)   # True (same object reference)
print("list2 is not list3 :", list2 is not list3)  # True

# Extra: Check memory addresses
print("\nMemory Locations (id function):")
print("id(list1) =", id(list1))
print("id(list2) =", id(list2))
print("id(list3) =", id(list3))

Program to check the number is positive

number = int(input('Enter a number: '))
# check if number is greater than 0
if number > 0:
    print(f'{number} is a positive number.')

print('A statement outside the if statement.')

Program to check voting eligibility with name

# Taking input from user
name = input("Enter your name: ")
age = int(input("Enter your age: "))

# Checking eligibility
if age >= 18:
    print("✅ Hi", name + ", you are eligible to vote.")
else:
    print("❌ Hi", name + ", you are not eligible to vote. Please wait until you are 18.")

Program to display grade based on marks

# Taking marks input
marks = int(input("Enter your marks: "))

# Checking grade using if-elif
if marks >= 90:
    print("Grade: A+ (Excellent)")
elif marks >= 75:
    print("Grade: A (Very Good)")
elif marks >= 60:
    print("Grade: B (Good)")
elif marks >= 45:
    print("Grade: C (Average)")
elif marks >= 33:
    print("Grade: D (Pass)")
else:
    print("Grade: F (Fail)")

Food Menu Program using if-elif

print("🍔 Welcome to Python Cafe 🍕")
print("Please choose an item from the menu:")
print("1. Burger - Rs. 100")
print("2. Pizza - Rs. 200")
print("3. Sandwich - Rs. 50")
print("4. Coffee - Rs. 30")

# Taking user choice
choice = int(input("Enter your choice (1-4): "))

# Checking menu using if-elif
if choice == 1:
    print("You selected Burger. Please pay Rs. 100.")
elif choice == 2:
    print("You selected Pizza. Please pay Rs. 200.")
elif choice == 3:
    print("You selected Sandwich. Please pay Rs. 50.")
elif choice == 4:
    print("You selected Coffee. Please pay Rs. 30.")
else:
    print("❌ Invalid choice! Please select from 1 to 4.")

Advanced ATM Program with Account Details & ATM Slip

# Account Information
account_holder = "Saubhagya Das"
account_number = "1234567890"
bank_name = "Python Bank"

# Default PIN and balance
correct_pin = 1234
balance = 5000
transactions = []  # store mini statement

# Step 1: PIN Verification
pin = int(input("Enter your ATM PIN: "))

if pin == correct_pin:
    print(f"✅ Welcome {account_holder} to {bank_name} ATM!")

    while True:
        # Display Menu
        print("\n===== ATM MENU =====")
        print("1. Check Balance")
        print("2. Deposit Money")
        print("3. Withdraw Money")
        print("4. Change PIN")
        print("5. Mini Statement (ATM Slip)")
        print("6. Exit")

        choice = int(input("Enter your choice (1-6): "))

        # Option 1: Check Balance
        if choice == 1:
            print("💰 Your Current Balance is:", balance)

        # Option 2: Deposit
        elif choice == 2:
            deposit = int(input("Enter amount to deposit: "))
            if deposit > 0:
                balance += deposit
                transactions.append(f"Deposited: Rs.{deposit}")
                print("✅ Successfully Deposited:", deposit)
                print("💰 Updated Balance:", balance)
            else:
                print("❌ Invalid Deposit Amount!")

        # Option 3: Withdraw
        elif choice == 3:
            withdraw = int(input("Enter amount to withdraw: "))
            if withdraw <= balance:
                if withdraw % 100 == 0:  # ATM only gives multiples of 100
                    balance -= withdraw
                    transactions.append(f"Withdrawn: Rs.{withdraw}")
                    print("💵 Please collect your cash:", withdraw)
                    print("💰 Remaining Balance:", balance)
                else:
                    print("❌ Enter amount in multiples of 100!")
            else:
                print("❌ Insufficient Balance! Your balance is:", balance)

        # Option 4: Change PIN
        elif choice == 4:
            old_pin = int(input("Enter your current PIN: "))
            if old_pin == correct_pin:
                new_pin = int(input("Enter your new PIN: "))
                confirm_pin = int(input("Confirm your new PIN: "))
                if new_pin == confirm_pin:
                    correct_pin = new_pin
                    print("✅ PIN successfully changed!")
                else:
                    print("❌ PINs do not match. Try again!")
            else:
                print("❌ Incorrect current PIN!")

        # Option 5: Mini Statement (ATM Slip Style)
        elif choice == 5:
            print("\n===================================")
            print(f"🏦 {bank_name}")
            print("-----------------------------------")
            print(f"Account Holder : {account_holder}")
            print(f"Account Number : XXXX{account_number[-4:]}")  # hide digits
            print("-----------------------------------")
            print("📜 Last Transactions:")
            if len(transactions) == 0:
                print("No transactions yet.")
            else:
                for t in transactions[-5:]:  # Show last 5 transactions
                    print("-", t)
            print("-----------------------------------")
            print("💰 Current Balance:", balance)
            print("===================================")

        # Option 6: Exit
        elif choice == 6:
            print("\n🙏 Thank you for using", bank_name, "ATM. Goodbye!")
            break

        else:
            print("❌ Invalid choice! Please select between 1-6.")

else:
    print("❌ Invalid PIN! Access Denied.")

While loop example: Print numbers from 1 to 10

i = 1   # initialization

while i <= 10:    # condition
    print("Number:", i)
    i += 1        # increment

Factorial of a number using while loop

# Taking input
n = int(input("Enter a number: "))

fact = 1   # store factorial
i = 1      # initialization

while i <= n:   # condition
    fact *= i   # multiply
    i += 1      # increment

print("Factorial of", n, "is:", fact)

Reverse of a number using while loop

# Taking input
num = int(input("Enter a number: "))

rev = 0   # to store reversed number

while num > 0:
    digit = num % 10        # get last digit
    rev = (rev * 10) + digit  # build reverse
    num //= 10              # remove last digit

print("Reverse of the number is:", rev)

Armstrong numbers in a given range using while loop

# Taking input
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

print("✅ Armstrong numbers between", start, "and", end, "are:")

num = start
while num <= end:
    original = num
    result = 0
    digits = len(str(num))  # number of digits
    temp = num

    while temp > 0:
        digit = temp % 10
        result += digit ** digits
        temp //= 10

    if original == result:
        print(original, end=" ")

    num += 1

Print numbers from 1 to 10 using for loop

for i in range(1, 11):   # range(start, end) → end is excluded
    print(i)

Print even and odd numbers using for loop

# Even numbers from 1 to 20
print("Even Numbers:")
for i in range(1, 21):
    if i % 2 == 0:
        print(i, end=" ")

print("\n")  # new line

# Odd numbers from 1 to 20
print("Odd Numbers:")
for i in range(1, 21):
    if i % 2 != 0:
        print(i, end=" ")

Nested for loop to print a star pattern

rows = int(input("Enter number of rows: "))

for i in range(1, rows + 1):     # outer loop for rows
    for j in range(1, i + 1):    # inner loop for columns
        print("*", end=" ")      # print star in same line
    print()   # move to next line

Pyramid star pattern using nested for loop

rows = int(input("Enter number of rows: "))

for i in range(1, rows + 1):      # outer loop for rows
    # print spaces (to center align stars)
    for j in range(rows - i):
        print(" ", end=" ")
    # print stars
    for k in range(2 * i - 1):
        print("*", end=" ")
    print()   # move to next line

Reverse pyramid star pattern using nested for loop

rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):       # outer loop (from rows to 1)
    # print spaces (to center align)
    for j in range(rows - i):
        print(" ", end=" ")
    # print stars
    for k in range(2 * i - 1):
        print("*", end=" ")
    print()   # move to next line

Calculator with loop and functions

# Functions
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b if b != 0 else "❌ Cannot divide by zero"

# Main Program
while True:
    print("\n===== Calculator =====")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("5. Exit")

    choice = int(input("Enter your choice (1-5): "))

    if choice == 5:
        print("🙏 Thank you for using the Calculator!")
        break

    x = float(input("Enter first number: "))
    y = float(input("Enter second number: "))

    if choice == 1:
        print("✅ Result =", add(x, y))
    elif choice == 2:
        print("✅ Result =", subtract(x, y))
    elif choice == 3:
        print("✅ Result =", multiply(x, y))
    elif choice == 4:
        print("✅ Result =", divide(x, y))
    else:
        print("❌ Invalid choice! Try again.")

Python Program: Call by Value vs Call by Reference

# Call by Value Example (Immutable types)
def change_number(n):
    print("Inside function before change:", n)
    n = n + 10   # modify
    print("Inside function after change:", n)

# Call by Reference Example (Mutable types)
def change_list(mylist):
    print("Inside function before change:", mylist)
    mylist.append(100)   # modify original list
    print("Inside function after change:", mylist)

# Main Program
# Immutable Example
num = 50
print("Original number before function call:", num)
change_number(num)
print("Original number after function call:", num)

print("\n----------------------------\n")

# Mutable Example
lst = [10, 20, 30]
print("Original list before function call:", lst)
change_list(lst)
print("Original list after function call:", lst)

Function with required arguments

def shopping_bill(item, price, quantity):
    total = price * quantity
    print(f"🛒 Item: {item}")
    print(f"💰 Price per unit: ₹{price}")
    print(f"📦 Quantity: {quantity}")
    print(f"✅ Total Bill = ₹{total}\n")

# Main Program
print("=== Online Shopping Bill ===")

# Customer 1
shopping_bill("Laptop", 50000, 1)

# Customer 2
shopping_bill("Headphones", 1500, 2)

# Customer 3
shopping_bill("Shoes", 2000, 3)

Function to calculate total bill with default GST and tip

def calculate_bill(amount, gst=5, tip=10):
    gst_amount = (gst / 100) * amount
    tip_amount = (tip / 100) * amount
    total = amount + gst_amount + tip_amount
    return total

# Main Program
print("=== Restaurant Bill Calculator ===")
bill1 = calculate_bill(1000, 12, 15)   # user gives GST=12% and Tip=15%
bill2 = calculate_bill(2000, 18)       # user gives GST=18%, default Tip=10%
bill3 = calculate_bill(1500)           # uses default GST=5% and Tip=10%

print("Customer 1 Total Bill = ₹", bill1)
print("Customer 2 Total Bill = ₹", bill2)
print("Customer 3 Total Bill = ₹", bill3)

Function using keyword arguments

def book_ticket(name, destination, price):
    print("✈️ Flight Ticket Booking")
    print(f"👤 Passenger Name: {name}")
    print(f"📍 Destination: {destination}")
    print(f"💰 Ticket Price: ₹{price}\n")

# Main Program
print("=== Flight Booking System ===")

# Using keyword arguments (order can be changed)
book_ticket(name="Rohit", destination="Delhi", price=5000)
book_ticket(price=7500, name="Anita", destination="Mumbai")
book_ticket(destination="Bengaluru", price=6500, name="Saubhagya")

Function using variable-length arguments

def restaurant_bill(customer_name, *items, **charges):
    print(f"🧾 Bill for {customer_name}")
    
    total = 0
    print("\nOrdered Items:")
    for item in items:
        print(f"🍴 {item[0]} - ₹{item[1]} x {item[2]}")
        total += item[1] * item[2]   # price * quantity
    
    # Apply extra charges (kwargs)
    for key, value in charges.items():
        print(f"{key} : {value}%")
        total += (value / 100) * total
    
    print(f"\n✅ Final Bill Amount = ₹{round(total, 2)}\n")

# Main Program
print("=== Restaurant Billing System ===")

# Customer 1 (no extra charges, only items)
restaurant_bill("Rohit", ("Pizza", 250, 2), ("Pasta", 150, 1))

# Customer 2 (with GST and Tip)
restaurant_bill("Anita", ("Burger", 120, 2), ("Coke", 50, 3), GST=5, Tip=10)

# Customer 3 (multiple items + GST only)
restaurant_bill("Saubhagya", ("Thali", 200, 2), ("IceCream", 80, 2), GST=12)

Lambda function to calculate discounted price

discount = lambda price: price - (price * 0.10)

# Real-world usage: Shopping items
items = {
    "Shoes": 2000,
    "Shirt": 1200,
    "Jeans": 2500,
    "Watch": 3000
}

print("=== Shopping Bill with 10% Discount ===")
for item, price in items.items():
    final_price = discount(price)
    print(f"{item}: Original ₹{price} -> After Discount ₹{final_price}")

Banking System Example using map() + filter() + reduce() with lambda.

from functools import reduce

# Bank accounts with customer name and balance
accounts = {
    "Ganesh": 8500,
    "Satya": 15000,
    "Saraswati": 12000,
    "Priya": 9500,
    "Jyoti": 20000
}

print("=== Original Bank Accounts ===")
for name, balance in accounts.items():
    print(f"{name}: ₹{balance}")

# 1. Apply 5% annual interest using map + lambda
updated_accounts = dict(
    map(lambda acc: (acc[0], acc[1] + (acc[1] * 0.05)), accounts.items())
)

print("\n=== After Adding 5% Interest ===")
for name, balance in updated_accounts.items():
    print(f"{name}: ₹{balance:.2f}")

# 2. Filter accounts with balance >= 10000
eligible_accounts = dict(filter(lambda acc: acc[1] >= 10000, updated_accounts.items()))

print("\n=== Eligible Accounts (Balance ≥ ₹10,000) ===")
for name, balance in eligible_accounts.items():
    print(f"{name}: ₹{balance:.2f}")

# 3. Calculate total money in the bank using reduce + lambda
total_balance = reduce(lambda x, y: x + y, eligible_accounts.values())

print("\n=== Bank Report ===")
print(f"Total Money from Eligible Accounts: ₹{total_balance:.2f}")

Student File Program

# Step 1: Write data to a file
with open("students.txt", "w") as file:
    file.write("Ganesh\n")
    file.write("Satya\n")
    file.write("Saraswati\n")
    file.write("Priya\n")
    file.write("Jyoti\n")

print("✅ Data written to file successfully!")

# Step 2: Read data from the file
with open("students.txt", "r") as file:
    print("\n=== Reading File Content ===")
    content = file.read()
    print(content)

# Step 3: Append more data to the file
with open("students.txt", "a") as file:
    file.write("New Student: Ramesh\n")

print("✅ Data appended successfully!")

# Step 4: Read again after appending
with open("students.txt", "r") as file:
    print("\n=== File Content After Appending ===")
    print(file.read())

Student Marks File

# Step 1: Write student marks to a file
with open("student_marks.txt", "w") as file:
    file.write("Ganesh: 85\n")
    file.write("Satya: 72\n")
    file.write("Saraswati: 90\n")
    file.write("Priya: 65\n")
    file.write("Jyoti: 78\n")

print("✅ Student marks written to file successfully!")

# Step 2: Read and display marks
print("\n=== Student Marks Report ===")
with open("student_marks.txt", "r") as file:
    for line in file:
        name, marks = line.strip().split(":")
        print(f"👩‍🎓 {name} scored {marks.strip()} marks")

# Step 3: Append new student marks
with open("student_marks.txt", "a") as file:
    file.write("Ramesh: 82\n")

print("\n✅ New student marks appended successfully!")

# Step 4: Display updated file content
print("\n=== Updated Student Marks Report ===")
with open("student_marks.txt", "r") as file:
    print(file.read())

Menu-Driven Student Management System

# Student Management System using File Handling

FILENAME = "students_db.txt"

# Function to add a new student
def add_student():
    name = input("Enter Student Name: ")
    age = input("Enter Age: ")
    course = input("Enter Course: ")
    with open(FILENAME, "a") as file:
        file.write(f"Name: {name}, Age: {age}, Course: {course}\n")
    print("✅ Student record added successfully!\n")

# Function to display all students
def display_students():
    try:
        with open(FILENAME, "r") as file:
            data = file.read()
            if data.strip() == "":
                print("⚠ No student records found.\n")
            else:
                print("\n=== Student Records ===")
                print(data)
    except FileNotFoundError:
        print("⚠ No records found! Please add students first.\n")

# Function to search a student by name
def search_student():
    search_name = input("Enter name to search: ").strip()
    found = False
    try:
        with open(FILENAME, "r") as file:
            for line in file:
                if search_name.lower() in line.lower():
                    print("🔍 Found:", line.strip())
                    found = True
        if not found:
            print("❌ Student not found.\n")
    except FileNotFoundError:
        print("⚠ No records found! Please add students first.\n")

# Main menu
while True:
    print("===== Student Management System =====")
    print("1. Add Student")
    print("2. Display All Students")
    print("3. Search Student")
    print("4. Exit")
    choice = input("Enter your choice (1-4): ")

    if choice == "1":
        add_student()
    elif choice == "2":
        display_students()
    elif choice == "3":
        search_student()
    elif choice == "4":
        print("👋 Exiting program. Goodbye!")
        break
    else:
        print("⚠ Invalid choice! Please try again.\n")

Library Management System using File Handling

FILENAME = "library.txt"

# Function to add a new book
def add_book():
    book_id = input("Enter Book ID: ")
    title = input("Enter Book Title: ")
    author = input("Enter Author Name: ")
    status = "Available"
    with open(FILENAME, "a") as file:
        file.write(f"ID: {book_id}, Title: {title}, Author: {author}, Status: {status}\n")
    print("✅ Book added successfully!\n")

# Function to display all books
def display_books():
    try:
        with open(FILENAME, "r") as file:
            data = file.read()
            if data.strip() == "":
                print("⚠ No books found in the library.\n")
            else:
                print("\n=== Library Books ===")
                print(data)
    except FileNotFoundError:
        print("⚠ No records found! Please add books first.\n")

# Function to search for a book
def search_book():
    search_title = input("Enter book title to search: ").strip()
    found = False
    try:
        with open(FILENAME, "r") as file:
            for line in file:
                if search_title.lower() in line.lower():
                    print("🔍 Found:", line.strip())
                    found = True
        if not found:
            print("❌ Book not found.\n")
    except FileNotFoundError:
        print("⚠ No records found! Please add books first.\n")

# Function to borrow a book
def borrow_book():
    borrow_title = input("Enter book title to borrow: ").strip()
    found = False
    try:
        with open(FILENAME, "r") as file:
            lines = file.readlines()
        with open(FILENAME, "w") as file:
            for line in lines:
                if borrow_title.lower() in line.lower() and "Available" in line:
                    updated = line.replace("Available", "Borrowed")
                    file.write(updated)
                    found = True
                else:
                    file.write(line)
        if found:
            print(f"📚 You borrowed '{borrow_title}'.\n")
        else:
            print("❌ Book not available or not found.\n")
    except FileNotFoundError:
        print("⚠ No records found! Please add books first.\n")

# Function to return a book
def return_book():
    return_title = input("Enter book title to return: ").strip()
    found = False
    try:
        with open(FILENAME, "r") as file:
            lines = file.readlines()
        with open(FILENAME, "w") as file:
            for line in lines:
                if return_title.lower() in line.lower() and "Borrowed" in line:
                    updated = line.replace("Borrowed", "Available")
                    file.write(updated)
                    found = True
                else:
                    file.write(line)
        if found:
            print(f"✅ You returned '{return_title}'.\n")
        else:
            print("❌ Book not found or was not borrowed.\n")
    except FileNotFoundError:
        print("⚠ No records found! Please add books first.\n")

# Main menu
while True:
    print("===== Library Management System =====")
    print("1. Add Book")
    print("2. Display All Books")
    print("3. Search Book")
    print("4. Borrow Book")
    print("5. Return Book")
    print("6. Exit")
    choice = input("Enter your choice (1-6): ")

    if choice == "1":
        add_book()
    elif choice == "2":
        display_books()
    elif choice == "3":
        search_book()
    elif choice == "4":
        borrow_book()
    elif choice == "5":
        return_book()
    elif choice == "6":
        print("👋 Exiting Library System. Goodbye!")
        break
    else:
        print("⚠ Invalid choice! Please try again.\n")

Phone Number Validator (India)

import re
import tkinter as tk
from tkinter import messagebox

def live_validate(*args):
    number = phone_var.get()
    cleaned = re.sub(r"[^\d+]", "", number)
    pattern = r"^(?:\+91|91)?[6-9]\d{0,9}$"
    if re.fullmatch(pattern, cleaned):
        status_label.config(text="✔ Valid so far", fg="green")
    else:
        status_label.config(text="❌ Invalid format", fg="red")

def final_validate():
    number = phone_var.get()
    cleaned = re.sub(r"[^\d+]", "", number)
    pattern = r"^(?:\+91|91)?[6-9]\d{9}$"
    if re.fullmatch(pattern, cleaned):
        messagebox.showinfo("Result", "✔ Valid Indian Mobile Number")
    else:
        messagebox.showerror("Result", "❌ Invalid Mobile Number")

# Tkinter GUI
app = tk.Tk()
app.title("Live Phone Number Validator")
app.geometry("400x200")
app.resizable(False, False)

title = tk.Label(app, text="Live Indian Phone Number Validator",
                 font=("Arial", 14, "bold"))
title.pack(pady=10)

phone_var = tk.StringVar()
phone_var.trace("w", live_validate)

entry = tk.Entry(app, textvariable=phone_var, font=("Arial", 12), width=30)
entry.pack(pady=5)

status_label = tk.Label(app, text="", font=("Arial", 12))
status_label.pack(pady=5)

btn = tk.Button(app, text="Validate", font=("Arial", 12, "bold"),
                command=final_validate, bg="green", fg="white")
btn.pack(pady=10)

app.mainloop()


Comments

Post a Comment

Popular posts from this blog

How to write and naming a java program

Java program can be created by using any editor.  The source code in java contains one or multiple number of classes.  Naming a java program Java program must be saved with a .java extension.  The primary name of the program must be same as class name if the class is declared as public.  It can be any name if no class is declared as public.  In one Java program there is only one public class.  How to compile a java program To compile a java program in command prompt (CMD)  Syntax- javac <file_name.java> Example- javac Hello.java How to run a java program To run a java program in command prompt Syntax- java class_name Example- java Hello

Command Prompt (CMD) Basic commands to Compile and Run java programs

How to change the drive in CMD (Command Prompt) To access another drive, type the drive’s letter, followed by : For instance, if you wanted to change the drive from C: to E:, you should type- Example-  E: ⤶ How to change the directory in CMD (CD in Command Prompt) The first command from the list is CD (Change Directory). This command enables you to change the current directory or, in other words, to navigate to another folder from your PC. Syntax- CD <Folder_Name> ⤶ Example- CD Saubhagya ⤶ How to go to the root of the drive in CMD (CD\) The first iteration of the CD command you should know is CD\. It takes you to the top of the directory tree. To see how it works, after you open the Command Prompt, type: Example- CD\ ⤶ How to change the parent directory in CMD (CD..) When you need to go one folder up, use the cd.. command. Let's assume that you’re inside the system32 folder and want to go back to the Windows folder. Type Example-  CD.. ⤶

Features of Java

  Features of Java The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords . A list of the most important features of the Java language is given below. Simple Object-Oriented Portable Platform independent Secured Robust Architecture neutral Interpreted High Performance Multithreaded Distributed Dynamic Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because: Java syntax is based on C++ (so easier for programmers to learn it after C++). Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc. There is no need to remove unreferenced objects because there is an Autom...