Python Programs
(loops, if-statements, files, strings, lists, and classes)
Program 1: Print numbers 1 to N**
# Program 1: Print numbers 1 to N using a for loop
n = int(input("Enter a number: "))
for i in range(1, n + 1):
print(i)
Program 2: Sum of first N natural numbers**
# Program 2: Sum of first N natural numbers using while loop
n = int(input("Enter N: "))
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum:", total)
Program 3: Multiplication table**
# Program 3: Print multiplication table of a number
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Program 4: Factorial using loop**
# Program 4: Factorial of a number using for loop
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is {factorial}")
1
Program 5: Fibonacci series**
# Program 5: Print Fibonacci series up to N terms
n = int(input("Enter number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
print()
Program 6: Sum of digits of a number**
# Program 6: Sum of digits using while loop
num = int(input("Enter a number: "))
total = 0
while num > 0:
total += num % 10
num //= 10
print("Sum of digits:", total)
Program 7: Reverse a number**
# Program 7: Reverse a number using while loop
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
reverse = reverse * 10 + num % 10
num //= 10
print("Reversed number:", reverse)
Program 8: Count even and odd numbers in a range**
# Program 8: Count even and odd numbers from 1 to N
n = int(input("Enter N: "))
even_count = 0
odd_count = 0
2
for i in range(1, n + 1):
if i % 2 == 0:
even_count += 1
else:
odd_count += 1
print(f"Even: {even_count}, Odd: {odd_count}")
Program 9: Print pattern using nested loops**
# Program 9: Right-angle triangle star pattern
n = int(input("Enter rows: "))
for i in range(1, n + 1):
for j in range(i):
print("*", end=" ")
print()
Program 10: Prime numbers in a range**
# Program 10: Print all prime numbers between 1 and N
n = int(input("Enter N: "))
for num in range(2, n + 1):
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
print()
Program 11: Check positive, negative, or zero**
# Program 11: Check if a number is positive, negative, or zero
num = float(input("Enter a number: "))
if num > 0:
3
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Program 12: Largest of three numbers**
# Program 12: Find the largest of three numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)
Program 13: Check leap year**
# Program 13: Check whether a year is a leap year
year = int(input("Enter year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a Leap Year")
else:
print(f"{year} is not a Leap Year")
Program 14: Simple calculator**
# Program 14: Simple calculator using if-elif
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")
4
if op == "+":
print("Result:", a + b)
elif op == "-":
print("Result:", a - b)
elif op == "*":
print("Result:", a * b)
elif op == "/":
if b != 0:
print("Result:", a / b)
else:
print("Error: Division by zero")
else:
print("Invalid operator")
Program 15: Grade calculator**
# Program 15: Assign grade based on marks
marks = float(input("Enter marks (0-100): "))
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
5
Program 16: Check vowel or consonant**
# Program 16: Check if a character is vowel or consonant
char = input("Enter a character: ").lower()
if char in "aeiou":
print(f"'{char}' is a Vowel")
elif [Link]():
print(f"'{char}' is a Consonant")
else:
print("Not a letter")
Program 17: Check Armstrong number**
# Program 17: Check if a number is Armstrong
num = int(input("Enter a number: "))
digits = len(str(num))
total = sum(int(d) ** digits for d in str(num))
if total == num:
print(f"{num} is an Armstrong number")
else:
print(f"{num} is not an Armstrong number")
Program 18: Check palindrome number**
# Program 18: Check if a number is a palindrome
num = input("Enter a number: ")
if num == num[::-1]:
print(f"{num} is a Palindrome")
else:
print(f"{num} is not a Palindrome")
Program 19: Eligibility for voting**
# Program 19: Check if a person is eligible to vote
age = int(input("Enter your age: "))
if age >= 18:
6
print("You are eligible to vote.")
else:
print(f"You need {18 - age} more year(s) to be eligible.")
Program 20: BMI Calculator**
# Program 20: Calculate BMI and classify
weight = float(input("Enter weight in kg: "))
height = float(input("Enter height in meters: "))
bmi = weight / (height ** 2)
print(f"BMI: {bmi:.2f}")
if bmi < 18.5:
print("Underweight")
elif bmi < 25:
print("Normal weight")
elif bmi < 30:
print("Overweight")
else:
print("Obese")
Program 21: Count vowels in a string**
# Program 21: Count vowels in a string
text = input("Enter a string: ")
count = sum(1 for ch in [Link]() if ch in "aeiou")
print("Number of vowels:", count)
Program 22: Reverse a string**
# Program 22: Reverse a string using slicing
text = input("Enter a string: ")
print("Reversed:", text[::-1])
Program 23: Check if string is palindrome**
# Program 23: Check palindrome string
text = input("Enter a string: ").lower().replace(" ", "")
7
if text == text[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
Program 24: Count words in a sentence**
# Program 24: Count the number of words in a sentence
sentence = input("Enter a sentence: ")
words = [Link]()
print("Word count:", len(words))
Program 25: Convert string to uppercase and lowercase**
# Program 25: String case conversion
text = input("Enter a string: ")
print("Uppercase:", [Link]())
print("Lowercase:", [Link]())
print("Title Case:", [Link]())
Program 26: Replace a word in a string**
# Program 26: Replace a word in a sentence
sentence = input("Enter a sentence: ")
old_word = input("Word to replace: ")
new_word = input("New word: ")
print("Updated:", [Link](old_word, new_word))
Program 27: Find frequency of each character**
# Program 27: Frequency of characters in a string
text = input("Enter a string: ")
freq = {}
for ch in text:
if ch != " ":
freq[ch] = [Link](ch, 0) + 1
for char, count in [Link]():
8
print(f"'{char}': {count}")
Program 28: Check if two strings are anagrams**
# Program 28: Anagram check
s1 = input("Enter first string: ").lower().replace(" ", "")
s2 = input("Enter second string: ").lower().replace(" ", "")
if sorted(s1) == sorted(s2):
print("Anagrams")
else:
print("Not Anagrams")
Program 29: Find max and min in a list**
# Program 29: Find max and min in a list
numbers = list(map(int, input("Enter numbers separated by
space: ").split()))
print("Max:", max(numbers))
print("Min:", min(numbers))
Program 30: Sort a list without using sort()**
# Program 30: Bubble sort
numbers = list(map(int, input("Enter numbers: ").split()))
n = len(numbers)
for i in range(n):
for j in range(0, n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1],
numbers[j]
print("Sorted:", numbers)
Program 31: Remove duplicates from a list**
# Program 31: Remove duplicates preserving order
numbers = list(map(int, input("Enter numbers: ").split()))
unique = []
for num in numbers:
9
if num not in unique:
[Link](num)
print("Without duplicates:", unique)
*Program 32: Find second largest element**
# Program 32: Second largest element in a list
numbers = list(map(int, input("Enter numbers: ").split()))
numbers = list(set(numbers))
[Link]()
if len(numbers) >= 2:
print("Second Largest:", numbers[-2])
else:
print("Not enough unique elements")
Program 33: Linear search in a list**
# Program 33: Linear search
numbers = list(map(int, input("Enter list elements:
").split()))
target = int(input("Enter number to search: "))
found = False
for i, num in enumerate(numbers):
if num == target:
print(f"Found at index {i}")
found = True
break
if not found:
print("Not found")
Program 34: Merge two lists and sort**
# Program 34: Merge and sort two lists
list1 = list(map(int, input("Enter first list: ").split()))
list2 = list(map(int, input("Enter second list: ").split()))
merged = sorted(list1 + list2)
10
print("Merged and sorted:", merged)
Program 35: Count occurrences of an element**
# Program 35: Count occurrences using loop
numbers = list(map(int, input("Enter list: ").split()))
target = int(input("Element to count: "))
count = 0
for num in numbers:
if num == target:
count += 1
print(f"{target} appears {count} time(s)")
Program 36: List comprehension — squares**
# Program 36: Generate squares using list comprehension
n = int(input("Enter N: "))
squares = [i ** 2 for i in range(1, n + 1)]
print("Squares:", squares)
Program 37: Write to a file**
# Program 37: Write text to a file
filename = input("Enter filename: ")
content = input("Enter content to write: ")
with open(filename, "w") as file:
[Link](content)
print(f"Written to {filename} successfully.")
Program 38: Read from a file**
# Program 38: Read and display file content
filename = input("Enter filename: ")
try:
with open(filename, "r") as file:
content = [Link]()
print("File Content:\n", content)
11
except FileNotFoundError:
print("File not found!")
Program 39: Count lines, words, and characters in a file**
# Program 39: File statistics
filename = input("Enter filename: ")
try:
with open(filename, "r") as file:
content = [Link]()
lines = [Link]("\n")
words = [Link]()
print(f"Lines: {len(lines)}")
print(f"Words: {len(words)}")
print(f"Characters: {len(content)}")
except FileNotFoundError:
print("File not found!")
Program 40: Append data to a file**
# Program 40: Append new content to an existing file
filename = input("Enter filename: ")
content = input("Enter content to append: ")
with open(filename, "a") as file:
[Link]("\n" + content)
print("Content appended successfully.")
Program 41: Copy content from one file to another**
# Program 41: File copy
source = input("Enter source filename: ")
dest = input("Enter destination filename: ")
try:
with open(source, "r") as src:
data = [Link]()
12
with open(dest, "w") as dst:
[Link](data)
print("File copied successfully.")
except FileNotFoundError:
print("Source file not found!")
Program 42: Search for a word in a file**
# Program 42: Search a word in a file
filename = input("Enter filename: ")
word = input("Enter word to search: ")
try:
with open(filename, "r") as file:
lines = [Link]()
found = False
for i, line in enumerate(lines, 1):
if word in line:
print(f"Found on line {i}: {[Link]()}")
found = True
if not found:
print("Word not found.")
except FileNotFoundError:
print("File not found!")
Program 43: Write a list to a file line by line**
# Program 43: Write list items to a file
filename = input("Enter filename: ")
items = input("Enter items separated by comma: ").split(",")
with open(filename, "w") as file:
for item in items:
[Link]([Link]() + "\n")
print("List written to file successfully.")
13
Program 44: Basic class — Student**
# Program 44: Student class with basic attributes and method
class Student:
def __init__(self, name, roll, marks):
[Link] = name
[Link] = roll
[Link] = marks
def display(self):
print(f"Name: {[Link]}, Roll: {[Link]}, Marks:
{[Link]}")
def grade(self):
if [Link] >= 90:
return "A+"
elif [Link] >= 75:
return "A"
elif [Link] >= 60:
return "B"
else:
return "C"
s = Student("Alice", 101, 88)
[Link]()
print("Grade:", [Link]())
Program 45: Class with inheritance — Animal**
# Program 45: Inheritance example with Animal and Dog
class Animal:
def __init__(self, name):
[Link] = name
14
def speak(self):
print(f"{[Link]} makes a sound.")
class Dog(Animal):
def speak(self):
print(f"{[Link]} says: Woof!")
class Cat(Animal):
def speak(self):
print(f"{[Link]} says: Meow!")
dog = Dog("Rex")
cat = Cat("Whiskers")
[Link]()
[Link]()
Program 46: Class with file operations — StudentRecord**
# Program 46: Save and load student records using a class
class StudentRecord:
def __init__(self, filename):
[Link] = filename
def save(self, name, marks):
with open([Link], "a") as file:
[Link](f"{name},{marks}\n")
print("Record saved.")
def display_all(self):
try:
15
with open([Link], "r") as file:
records = [Link]()
if not records:
print("No records found.")
else:
print("Name\t\tMarks")
print("-" * 25)
for record in records:
name, marks = [Link]().split(",")
print(f"{name}\t\t{marks}")
except FileNotFoundError:
print("No file found.")
sr = StudentRecord("[Link]")
[Link]("Alice", 90)
[Link]("Bob", 78)
sr.display_all()
Program 47: Class with list operations — ShoppingCart**
# Program 47: Shopping cart using class and list
class ShoppingCart:
def __init__(self):
[Link] = []
def add_item(self, item, price):
[Link]({"item": item, "price": price})
print(f"Added: {item} - ${price}")
def remove_item(self, item):
for i in [Link]:
16
if i["item"] == item:
[Link](i)
print(f"Removed: {item}")
return
print("Item not found.")
def total(self):
return sum(i["price"] for i in [Link])
def display(self):
print("\n--- Cart ---")
for i in [Link]:
print(f" {i['item']}: ${i['price']}")
print(f"Total: ${[Link]()}")
cart = ShoppingCart()
cart.add_item("Apple", 1.5)
cart.add_item("Milk", 2.0)
cart.add_item("Bread", 1.8)
[Link]()
cart.remove_item("Milk")
[Link]()
Program 48: Class with string processing — TextAnalyzer**
# Program 48: Text analyzer class
class TextAnalyzer:
def __init__(self, text):
[Link] = text
def word_count(self):
17
return len([Link]())
def char_count(self):
return len([Link])
def vowel_count(self):
return sum(1 for ch in [Link]() if ch in
"aeiou")
def most_common_word(self):
words = [Link]().split()
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
return max(freq, key=[Link])
def display_stats(self):
print(f"Words: {self.word_count()}")
print(f"Characters: {self.char_count()}")
print(f"Vowels: {self.vowel_count()}")
print(f"Most common word:
'{self.most_common_word()}'")
ta = TextAnalyzer("Python is great and Python is fun")
ta.display_stats()
Program 49: Class with loops — NumberOperations**
# Program 49: Math operations class using loops
class NumberOperations:
def __init__(self, numbers):
[Link] = numbers
18
def total(self):
s = 0
for n in [Link]:
s += n
return s
def average(self):
return [Link]() / len([Link])
def get_evens(self):
return [n for n in [Link] if n % 2 == 0]
def get_odds(self):
return [n for n in [Link] if n % 2 != 0]
def display(self):
print("Numbers:", [Link])
print("Sum:", [Link]())
print("Average:", [Link]())
print("Evens:", self.get_evens())
print("Odds:", self.get_odds())
ops = NumberOperations([10, 3, 7, 22, 5, 18, 9])
[Link]()
Program 50: Complete OOP — Bank Account**
# Program 50: Bank Account class (complete OOP example)
class BankAccount:
bank_name = "Python National Bank" # Class variable
19
def __init__(self, owner, balance=0):
[Link] = owner
[Link] = balance
[Link] = []
def deposit(self, amount):
if amount > 0:
[Link] += amount
[Link](f"Deposited: ${amount}")
print(f"Deposited ${amount}. New balance:
${[Link]}")
else:
print("Invalid deposit amount.")
def withdraw(self, amount):
if amount > [Link]:
print("Insufficient funds!")
elif amount <= 0:
print("Invalid amount.")
else:
[Link] -= amount
[Link](f"Withdrew: ${amount}")
print(f"Withdrew ${amount}. New balance:
${[Link]}")
def save_statement(self):
filename = f"{[Link]}_statement.txt"
with open(filename, "w") as file:
[Link](f"Bank: {BankAccount.bank_name}\n")
20
[Link](f"Account Owner: {[Link]}\n")
[Link](f"Current Balance:
${[Link]}\n\n")
[Link]("Transaction History:\n")
for t in [Link]:
[Link](f" - {t}\n")
print(f"Statement saved to {filename}")
def display(self):
print(f"\n--- {BankAccount.bank_name} ---")
print(f"Owner: {[Link]}")
print(f"Balance: ${[Link]}")
print("Transaction History:")
for t in [Link]:
print(f" - {t}")
# Main program
acc = BankAccount("Alice", 500)
[Link](200)
[Link](100)
[Link](700)
[Link](50)
[Link]()
acc.save_statement()
21