0% found this document useful (0 votes)
3 views21 pages

Python Training Program Solutions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views21 pages

Python Training Program Solutions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python 12 Days Practice Programs with Solutions​

Day 1: Practice Programs and Solutions


1. Print "Hello, World!"
print("Hello, World!")​
Output:​
Hello, World!

2. Add two numbers entered by user


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

Sample Input:​
Enter first number: 5​
Enter second number: 10​
Output:​
Sum: 15

3. Find the type of a variable


x = 10
print("Type of x is", type(x))​
Output:​
Type of x is <class 'int'>

4. Calculate area of a circle


radius = float(input("Enter radius of circle: "))
area = 3.14159 * radius * radius
print("Area of circle:", area)​

Sample Input:
Enter radius of circle: 3​
Output:​
Area of circle: 28.27431

5. Swap two variables


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Before swapping: a =", a, ", b =", b)
a, b = b, a
print("After swapping: a =", a, ", b =", b)​

Sample Input:​
Enter first number: 7​
Enter second number: 9​
Output:​
Before swapping: a = 7 , b = 9​
After swapping: a = 9 , b = 7

Day 2: Practice Programs and Solutions


1. Simple calculator (add, sub, mul, div)
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
if b != 0:
print("Division:", a / b)
else:
print("Division by zero is not allowed.")

Sample Input:​
Enter first number: 8​
Enter second number: 2​
Output:​
Addition: 10.0​
Subtraction: 6.0​
Multiplication: 16.0​
Division: 4.0

2. Check if a number is even or odd


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

Sample Input:​
Enter a number: 7​
Output:​
7 is Odd
3. Find largest of two numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

if a > b:
print(a, "is larger")
elif b > a:
print(b, "is larger")
else:
print("Both numbers are equal")

Sample Input:​
Enter first number: 12​
Enter second number: 5​
Output:​
12 is larger

4. Convert Celsius to Fahrenheit


celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)

Sample Input:​
Enter temperature in Celsius: 0​
Output:​
Temperature in Fahrenheit: 32.0

5. Evaluate simple expressions


result = (5 + 3) * 2 - (8 / 4)
print("Result of expression:", result)
Output:​
Result of expression: 14.0​

Day 3: Practice Programs and Solutions


1. Print numbers from 1 to 10 using a while loop

# Program 1: Print numbers from 1 to 10 using while loop

i=1
while i <= 10:
print(i)
i += 1

Output:

1
2
3
4
5
6
7
8
9
10

2. Print even numbers from 1 to 20 using for loop

# Program 2: Print even numbers from 1 to 20 using for loop

for num in range(1, 21):


if num % 2 == 0:
print(num)

Output:

2
4
6
8
10
12
14
16
18
20

3. Sum of numbers from 1 to n

# Program 3: Sum of numbers from 1 to n

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


sum = 0

for i in range(1, n + 1):


sum += i
print("Sum from 1 to", n, "is", sum)

Sample Output (if n = 5):

Enter a number: 5
Sum from 1 to 5 is 15

4. Print multiplication table of a number

# Program 4: Print multiplication table of a number

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

print("Multiplication Table of", num)


for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

Sample Output (if num = 4):

Enter a number: 4
Multiplication Table of 4
4x1=4
4x2=8
...
4 x 10 = 40

5. Nested loop to print a pattern

# Program 5: Nested loop to print pattern

rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()

Output:

*
**
***
****
*****

Day 4: Practice Programs and Solutions


1. Reverse a string
text = input("Enter a string: ")
reversed_text = text[::-1]
print("Reversed string:", reversed_text)

Output:

Enter a string: python


Reversed string: nohtyp

2. Check if string is palindrome


text = input("Enter a string: ")
if text == text[::-1]:
print("Palindrome")
else:
print("Not a palindrome")

Output:

Enter a string: madam


Palindrome

3. Count vowels in a string


text = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
print("Number of vowels:", count)

Output:

Enter a string: education


Number of vowels: 5

4. String slicing examples


text = "PythonProgramming"
print("First 6 characters:", text[:6])
print("Last 6 characters:", text[-6:])
print("Characters from index 2 to 8:", text[2:9])

Output:
First 6 characters: Python
Last 6 characters: mming
Characters from index 2 to 8: thonPro

5. String method examples


text = " hello world "
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
print("Stripped:", text.strip())
print("Replaced:", text.replace("world", "Python"))

Output:

Uppercase: HELLO WORLD


Lowercase: hello world
Stripped: hello world
Replaced: hello Python

6. Take a string input and print its length


text = input("Enter a string: ")
print("Length of the string:", len(text))

Output:

Enter a string: Hello World


Length of the string: 11

7. Convert a string to uppercase and lowercase


text = input("Enter a string: ")
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())

Output:

Enter a string: Python


Uppercase: PYTHON
Lowercase: python

8. Check if a substring exists in the main string


main_string = input("Enter the main string: ")
substring = input("Enter the substring to search: ")

if substring in main_string:
print("Substring found.")
else:
print("Substring not found.")

Output:

Enter the main string: Hello Python


Enter the substring to search: Python
Substring found.

9. Replace all vowels in a string with '*'


text = input("Enter a string: ")
vowels = "aeiouAEIOU"
result = ""
for char in text:
if char in vowels:
result += '*'
else:
result += char
print("Modified string:", result)

Output:

Enter a string: Education


Modified string: *d*c*t**n

10. Split a string into words and count them


text = input("Enter a sentence: ")
words = text.split()
print("Words:", words)
print("Total number of words:", len(words))

Output:

Enter a sentence: Python is fun to learn


Words: ['Python', 'is', 'fun', 'to', 'learn']
Total number of words: 5

Day 5: List and Tuple Practice Program Solutions


1. Create a list of 5 elements and print them

my_list = [10, 20, 30, 40, 50]


print("List elements:", my_list)
Output:​
List elements: [10, 20, 30, 40, 50]

2. Find max and min element from list

numbers = [5, 12, 7, 20, 3]


print("Maximum:", max(numbers))
print("Minimum:", min(numbers))

Output:​
Maximum: 20​
Minimum: 3

3. Sort list in ascending and descending order

data = [8, 3, 1, 7, 5]
data.sort()
print("Ascending:", data)

data.sort(reverse=True)
print("Descending:", data)

Output:​
Ascending: [1, 3, 5, 7, 8]​
Descending: [8, 7, 5, 3, 1]

4. Remove duplicates from a list

dup_list = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(dup_list))
print("List without duplicates:", unique_list)

Output:​
List without duplicates: [1, 2, 3, 4, 5]

5. Sum all elements in a list

nums = [4, 6, 2, 9]
total = sum(nums)
print("Sum of elements:", total)

Output:​
Sum of elements: 21
Tuple Practice Questions and Solutions

1. Access the third element from the tuple

t = (10, 20, 30, 40, 50)


print("Third element:", t[2])

Output:​
Third element: 30

2. Check if a value exists in a tuple

t = (10, 20, 25, 30, 35)


if 25 in t:
print("25 exists in the tuple")
else:
print("25 does not exist")

Output:​
25 exists in the tuple

3. Count how many times 4 appears

t = (1, 4, 6, 4, 3, 4)
count = t.count(4)
print("4 appears", count, "times")

Output:​
4 appears 3 times

4. Unpack a tuple into variables

person = ('John', 22, 'India')


name, age, country = person​

print("Name:", name)
print("Age:", age)
print("Country:", country)

Output:​
Name: John​
Age: 22​
Country: India
5. Find the maximum and minimum values

t = (12, 45, 2, 30, 67)


print("Maximum:", max(t))
print("Minimum:", min(t))

Output:​
Maximum: 67​
Minimum: 2

Day 6 – Practice Program Solutions


Topic: Sets and Dictionaries in Python

1. Create a set and perform basic operations


my_set = {1, 2, 3, 4}
print("Original Set:", my_set)

# Add element
my_set.add(5)
print("After Adding 5:", my_set)

# Remove element
my_set.remove(2)
print("After Removing 2:", my_set)

# Check membership
print("Is 3 in set?", 3 in my_set)

Output:​
Original Set: {1, 2, 3, 4}​
After Adding 5: {1, 2, 3, 4, 5}​
After Removing 2: {1, 3, 4, 5}​
Is 3 in set? True

2. Perform union and intersection of two sets


set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
intersection_set = set1.intersection(set2)

print("Union:", union_set)
print("Intersection:", intersection_set)

Output:​
Union: {1, 2, 3, 4, 5}​
Intersection: {3}

3. Add and remove elements from a dictionary


my_dict = {'a': 1, 'b': 2}
print("Original Dictionary:", my_dict)

# Add key-value
my_dict['c'] = 3
print("After Adding 'c':", my_dict)

# Remove key
del my_dict['a']
print("After Removing 'a':", my_dict)

Output:​
Original Dictionary: {'a': 1, 'b': 2}​
After Adding 'c': {'a': 1, 'b': 2, 'c': 3}​
After Removing 'a': {'b': 2, 'c': 3}

4. Count word frequencies using a dictionary


text = "apple banana apple orange banana apple"
words = text.split()

frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1

print("Word Frequencies:", frequency)

Output:​
Word Frequencies: {'apple': 3, 'banana': 2, 'orange': 1}
5. Merge two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}

# Merge using unpacking (Python 3.5+)


merged_dict = {**dict1, **dict2}
print("Merged Dictionary:", merged_dict)

Output:​
Merged Dictionary: {'a': 1, 'b': 3, 'c': 4}

Day 7: Functions and Recursion Program Solutions


1. Create a Function to Add Two Numbers

def add_numbers(a, b):


return a + b

print("Sum:", add_numbers(10, 5))

Output:​
Sum: 15

2. Function to Check Prime Number

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True

print("Is 7 prime?", is_prime(7))

Output:​
Is 7 prime? True

3. Recursive Function for Factorial

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

print("Factorial of 5:", factorial(5))

Output:​
Factorial of 5: 120

4. Function to Check Palindrome

def is_palindrome(s):
return s == s[::-1]
print("Is 'radar' a palindrome?", is_palindrome("radar"))

Output:​
Is 'radar' a palindrome? True

5. Function to Find Sum of Digits of a Number (Recursive)

def sum_of_digits(n):
if n == 0:
return 0
return n % 10 + sum_of_digits(n // 10)

print("Sum of digits of 1234:", sum_of_digits(1234))

Output:​
Sum of digits of 1234: 10

6. Recursive Function to Print nth Fibonacci Number

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

print("6th Fibonacci number:", fibonacci(6))

Output:​
6th Fibonacci number: 8

Day 8: Introduction to OOP (Classes and


Objects)
Topics Covered:

●​ Classes and Objects


●​ Constructors (__init__)
●​ Defining Methods
●​ Object Creation and Usage

1. Create a class Student with name and marks


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

def display(self):
print(f"Name: {self.name}, Marks: {self.marks}")

s1 = Student("Alice", 85)
s1.display()

Output:​
Name: Alice, Marks: 85

2. Create a class Circle to calculate area and circumference


import math
class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2

def circumference(self):
return 2 * math.pi * self.radius

c1 = Circle(5)
print("Area:", c1.area())
print("Circumference:", c1.circumference())
Output:​
Area: 78.53981633974483​
Circumference: 31.41592653589793

3. Create a class BankAccount with deposit and withdraw methods


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

def deposit(self, amount):


self.balance += amount
print(f"{amount} deposited. New Balance: {self.balance}")

def withdraw(self, amount):


if amount <= self.balance:
self.balance -= amount
print(f"{amount} withdrawn. Remaining Balance:
{self.balance}")
else:
print("Insufficient balance")

acc = BankAccount("Bob", 1000)


acc.deposit(500)
acc.withdraw(300)

Output:​
500 deposited. New Balance: 1500​
300 withdrawn. Remaining Balance: 1200

4. Create a class Car with attributes and method to display


class Car:
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year

def display_info(self):
print(f"Car: {self.brand} {self.model} ({self.year})")

car1 = Car("Toyota", "Camry", 2021)


car1.display_info()

Output:​
Car: Toyota Camry (2021)

5. Create multiple objects and display their data


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

def show(self):
print(f"{self.name} is {self.age} years old.")

p1 = Person("John", 25)
p2 = Person("Emma", 30)
p3 = Person("Mike", 22)

p1.show()
p2.show()
p3.show()

Output:​
John is 25 years old.​
Emma is 30 years old.​
Mike is 22 years old.

Day 9: File Handling in Python


Practice Programs with Solutions

1. Write Text to a File


# write_text.py
with open("sample.txt", "w") as file:
file.write("Hello, this is a sample file.\nWelcome to Python
file handling.")
print("Text written to file successfully.")

Output:​
Text written to file successfully.

2. Read Content from a File


# read_file.py
with open("sample.txt", "r") as file:
content = file.read()
print("File content:\n", content)

Output:​
File content:​
Hello, this is a sample file.​
Welcome to Python file handling.

3. Append Data to a File


# append_file.py
with open("sample.txt", "a") as file:
file.write("\nThis line is added using append mode.")
print("Data appended successfully.")

Output:​
Data appended successfully.

4. Count Number of Words in a File


# count_words.py
with open("sample.txt", "r") as file:
content = file.read()
words = content.split()
print("Total number of words:", len(words))

Output:​
Total number of words: 16

5. Copy Content from One File to Another


# copy_file.py
with open("sample.txt", "r") as source_file:
data = source_file.read()

with open("copied_file.txt", "w") as dest_file:


dest_file.write(data)

print("File copied successfully.")

Output:​
File copied successfully

Day 10: Exception Handling in


Python

Practice Program Solutions

1. Divide two numbers and handle division by zero

try:

a = int(input("Enter numerator: "))

b = int(input("Enter denominator: "))

result = a / b

print("Result:", result)

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

Output Example:​
Enter numerator: 10​
Enter denominator: 0​
Error: Cannot divide by zero.

2. Handle invalid input using try-except

try:

num = int(input("Enter an integer: "))


print("You entered:", num)

except ValueError:

print("Error: Invalid input, please enter an integer.")

Output Example:​
Enter an integer: abc​
Error: Invalid input, please enter an integer.

3. Raise an exception if a number is negative

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

if num < 0:

raise ValueError("Negative number entered!")

else:

print("Number is positive:", num)

Output Example:​
Enter a positive number: -3​
Traceback (most recent call last):​
ValueError: Negative number entered!

4. Handle file not found error

try:

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

data = f.read()

print(data)

except FileNotFoundError:

print("Error: File not found.")

Output Example:​
Error: File not found.
5. Use finally block to close a file

try:

f = open("sample.txt", "r")

print("File content:", f.read())

except FileNotFoundError:

print("Error: sample.txt not found.")

finally:

try:

f.close()

print("File closed successfully.")

except NameError:

print("File was never opened.")

Output Example:​
Error: sample.txt not found.​
File was never opened.

You might also like