0% found this document useful (0 votes)
6 views

Python program

The document outlines a collection of Python programming exercises categorized into basic programs, control structures, lists and strings, functions and recursion, file handling, data structures, object-oriented programming, and miscellaneous programs. Each category contains specific tasks with explanations and code examples, covering fundamental concepts such as loops, conditionals, and file operations. The document serves as a comprehensive guide for beginners to practice and enhance their Python programming skills.

Uploaded by

anukumarinaira03
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python program

The document outlines a collection of Python programming exercises categorized into basic programs, control structures, lists and strings, functions and recursion, file handling, data structures, object-oriented programming, and miscellaneous programs. Each category contains specific tasks with explanations and code examples, covering fundamental concepts such as loops, conditionals, and file operations. The document serves as a comprehensive guide for beginners to practice and enhance their Python programming skills.

Uploaded by

anukumarinaira03
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Python program

Basic Programs

1. Hello World – Print "Hello, World!"


2. Sum of Two Numbers – Take two numbers as input and print their sum.
3. Check Even or Odd – Input a number and check whether it is even or odd.
4. Find the Largest of Three Numbers – Input three numbers and find the maximum.
5. Swap Two Numbers – Swap two numbers without using a third variable.

Control Structures (Loops and Conditional Statements)

6. Factorial of a Number – Using loops and recursion.


7. Prime Number Check – Check if a number is prime.
8. Fibonacci Series – Print Fibonacci series up to n terms.
9. Palindrome Number – Check if a number or string is a palindrome.
10. Armstrong Number – Check if a number is an Armstrong number.

Lists and Strings

11. Reverse a List – Reverse elements of a list without using the built-in function.
12. Find Largest and Smallest in a List – Find max and min values.
13. Sorting a List – Implement Bubble Sort or Selection Sort.
14. String Reversal – Reverse a string using slicing and loops.
15. Count Vowels and Consonants in a String

Functions and Recursion

16. Calculate GCD (HCF) and LCM


17. Recursive Function for Factorial
18. Recursive Function for Fibonacci Sequence
19. Check if a Number is Perfect, Armstrong, or Palindrome using Functions
20. Lambda Function Examples – Square of a number, sum of two numbers.

File Handling

21. Read and Write to a File – Open a file, write some data, and read it.
22. Count the Number of Lines, Words, and Characters in a File
23. Copy the Contents of One File to Another
24. Find and Replace a Word in a File
Data Structures (Lists, Tuples, Dictionaries, Sets)

25. Stack Implementation using List


26. Queue Implementation using List
27. Dictionary Operations – Add, remove, and search elements.
28. Tuple Operations – Indexing, slicing, and concatenation.
29. Set Operations – Union, Intersection, Difference.

Object-Oriented Programming (OOP)

30. Class and Object Example – Create a class and object with attributes and methods.
31. Bank Account Class – Implement deposit and withdraw functions.
32. Inheritance Example – Create a base class and derived class.
33. Method Overloading and Overriding
34. Operator Overloading Example

Miscellaneous Programs

35. Matrix Addition and Multiplication


36. Convert Decimal to Binary, Octal, Hexadecimal
37. Simple Calculator using Functions
38. Pattern Printing (Pyramid, Diamond, Floyd's Triangle, Pascal's Triangle)
39. Tic-Tac-Toe Game (Simple Python Game)
40. Generate Random Numbers using the random module

1. Basic Python Programs


1.1 Print "Hello, World!"

print "Hello, World!")

✅ Explanation: This is a simple program to print text using the print() function.

1.2 Add Two Numbers


python
CopyEdit
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
sum = a + b
print("Sum:", sum)

✅ Explanation: The program takes two inputs from the user, converts them to integers, adds
them, and prints the result.

1.3 Check Even or Odd


num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")

✅ Explanation: Uses modulus (%) operator to check if the number is divisible by 2.

1.4 Find the Largest of Three Numbers


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

largest = max(a, b, c) # Using max() function


print("Largest number is:", largest)

✅ Explanation: The max() function finds the largest among three numbers.

2. Control Structures
2.1 Factorial of a Number
python
CopyEdit
num = int(input("Enter a number: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)

✅ Explanation: Uses a loop to multiply numbers from 1 to num.

2.2 Prime Number Check


num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")

✅ Explanation: A number is prime if it's only divisible by 1 and itself.

3. Loops & Patterns


3.1 Fibonacci Series
n = int(input("Enter the number of terms: "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b

✅ Explanation: Each term is the sum of the previous two.

3.2 Palindrome Number


python
CopyEdit
num = input("Enter a number: ")
if num == num[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")

✅ Explanation: Uses slicing [::-1] to reverse the string.

4. String Operations
4.1 Reverse a String
text = input("Enter a string: ")
print("Reversed:", text[::-1])

✅ Explanation: Uses slicing to reverse the string.

4.2 Count Vowels and Consonants


text = input("Enter a string: ").lower()
vowels = "aeiou"
vowel_count = sum(1 for char in text if char in vowels)
consonant_count = len(text) - vowel_count
print("Vowels:", vowel_count, "Consonants:", consonant_count)

✅ Explanation: Counts vowels and subtracts from total length for consonants.

5. Functions & Recursion


5.1 Recursive Function for Factorial
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)

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


print("Factorial:", factorial(num))

✅ Explanation: Calls itself with n - 1 until n = 0.

5.2 Recursive Fibonacci Series


def fibonacci(n):
return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)

n = int(input("Enter terms: "))


for i in range(n):
print(fibonacci(i), end=" ")

✅ Explanation: Uses recursion to generate Fibonacci numbers.

6. File Handling
6.1 Read & Write to a File
with open("test.txt", "w") as f:
f.write("Hello, Python!")

with open("test.txt", "r") as f:


print(f.read())

✅ Explanation: Opens a file in write mode (w) and then reads it.
6.2 Count Words in a File

with open("sample.txt", "r") as file:


text = file.read()
words = text.split()
print("Word Count:", len(words))

✅ Explanation: Reads a file and splits text into words.

7. Data Structures (List, Tuple, Dictionary, Set)


7.1 Reverse a List

lst = [1, 2, 3, 4, 5]
print("Reversed List:", lst[::-1])

✅ Explanation: Uses slicing to reverse a list.

7.2 Dictionary Operations

d = {"name": "Alice", "age": 25}


d["city"] = "New York" # Adding an item
del d["age"] # Removing an item
print(d)

✅ Explanation: Adds and removes items from a dictionary.

8. Object-Oriented Programming (OOP)


8.1 Class and Object Example

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def display(self):
print("Name:", self.name, "Age:", self.age)

s1 = Student("John", 20)
s1.display()

✅ Explanation: Demonstrates class and object creation.

8.2 Bank Account Class


class BankAccount:
def __init__(self, balance=0):
self.balance = balance

def deposit(self, amount):


self.balance += amount

def withdraw(self, amount):


if self.balance >= amount:
self.balance -= amount
else:
print("Insufficient balance")

def get_balance(self):
return self.balance

acc = BankAccount()
acc.deposit(1000)
acc.withdraw(500)
print("Balance:", acc.get_balance())

✅ Explanation: Implements a simple bank account with deposit and withdrawal.

9. Miscellaneous Programs
9.1 Convert Decimal to Binary

num = int(input("Enter decimal number: "))


print("Binary:", bin(num)[2:])

✅ Explanation: Uses bin() to convert decimal to binary.

9.2 Pattern Printing (Pyramid)

n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "* " * i)

✅ Explanation: Prints a pyramid pattern using loops.

You might also like