Python Final
Python Final
"""
Module 2.1: Basic Expression Programs
"""
# Hello World
print("hello world")
# Output:
# hello world
# _____________________________________________________________
# Output:
# hello world how are you
# _____________________________________________________________
print("hello world")
print("how are you")
# Output:
# hello world
# how are you
# _____________________________________________________________
print("hello world")
print("\nhow are you")
# Output:
# hello world
# how are you
# _____________________________________________________________
# Output:
# hello world how are you
# _____________________________________________________________
1
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to read one number and display it
"""
n = int(input())
print(n)
"""
Write a program to read one number and display it (with messages)
"""
"""
Write a program to add two numbers
"""
2
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to multiply two numbers
"""
"""
Write a program to find area of a rectangle
"""
"""
Write a program to find volume of cube
"""
3
VELOCIS EDUCATION PYTHON NOTES
# enter breadth : 3
# volume of cube = 60
# _____________________________________________________________
"""
Write a program to find area of triangle
"""
"""
Write a program to calculate simple interest
"""
"""
Write a program to compute Fahrenheit from centigrade
"""
4
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to calculate area of circle
"""
"""
Module 2.2: Conditional Programs
(if, if-else, if-else if ladder, switch-case, goto)
"""
"""
Write a program to read marks of a student from keyboard whether the
student is pass (if)
"""
5
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to read marks of a student from keyboard whether the
student is pass or fail (if-else)
"""
"""
Write a program to read three numbers from keyboard and find out
maximum out of these three (nested if-else)
"""
6
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to read marks from keyboard and your program should
display equivalent grade according to following table:
Marks Grade
100-80 Distinction
60-79 First class
36-59 Second class
0-39 Fail
"""
"""
Write a program that reads a number from 1 to 7 and accordingly it
should display MONDAY To SUNDAY (switch-case)
"""
7
VELOCIS EDUCATION PYTHON NOTES
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}
print(days.get(day, "Invalid day number"))
print("Have a nice day")
"""
Check whether the given number is positive, negative or zero
"""
8
VELOCIS EDUCATION PYTHON NOTES
"""
Write a simple calculator (using if...else if)
"""
"""
Write a simple calculator (using switch-case)
"""
9
VELOCIS EDUCATION PYTHON NOTES
if op in operations:
res = operations[op](num1, num2) # Indented under if
print("Result :", res) # Indented under if
else:
print("Invalid choice . .") # Indented under else
"""
Write a program to find out given year, which is leap or not.
10
VELOCIS EDUCATION PYTHON NOTES
"""
Module 2.3: Loops
"""
"""
To read any five number and print the average value
"""
"""
Write a program to find out all the numbers divisible by 5 and 7
between 1 to 100
"""
# Output:
# 35
# 70
# _____________________________________________________________
"""
Find sum of digits of given numbers
"""
11
VELOCIS EDUCATION PYTHON NOTES
"""
To Find out the total number of odd digits within the given number and
print the sum of all odd digits
"""
"""
Reverse a number
"""
12
VELOCIS EDUCATION PYTHON NOTES
"""
Find out sum of first and last digit of a given number
"""
"""
WAP to find out largest digit in an given integer e.g. 1 2 3 4, 5 is
the greatest
"""
13
VELOCIS EDUCATION PYTHON NOTES
"""
Read five persons height and weight and count the number of persons
having greater than 170 and weight less than 50
"""
count = 0
for i in range(5):
h = float(input("Enter height: ")) # Indented under for
w = float(input("Enter weight: ")) # Indented under for
if h >= 170 and w <= 50: # Indented under for
count += 1 # Indented under if
print("Total persons =", count)
# Sample Output:
# Enter height: 175
# Enter weight: 48
# Enter height: 160
# Enter weight: 55
# Enter height: 172
# Enter weight: 49
# Enter height: 168
# Enter weight: 50
# Enter height: 180
# Enter weight: 45
# Total persons = 3
# _____________________________________________________________
"""
WAP to calculate average and total of 5 students for 3 subjects (Use 2
for loops)
"""
# Sample Output:
# Enter three marks for student #1: 80 85 90
# Average = 85
# _____________________________________________________________
14
VELOCIS EDUCATION PYTHON NOTES
"""
Check whether the given number is perfect or not. A number is perfect
if sum of its digits equals multiplication of digits
"""
"""
Check for Armstrong number, A number is Armstrong if sum of cube of
every digit is same as the original number.
E.g. 153 = 1^3 + 5^3 + 3^3 = 153
"""
15
VELOCIS EDUCATION PYTHON NOTES
else:
print("Not Armstrong") # Indented under else
"""
Module 2.4: Series
"""
"""
1+2+3+......+n
"""
"""
2+4+6+......+n
"""
16
VELOCIS EDUCATION PYTHON NOTES
"""
1+3+5+......+n
"""
"""
1^2 + 2^2 + 3^2 + 4^2 ....... +n^2
"""
"""
1+4-9+16-25+36...+n^2
"""
n = int(input("enter n : "))
sum_series = 1
sign = 1
for i in range(2, n+1):
sum_series += (i * i) * sign # Indented under for
sign *= -1 # Indented under for
print("sum=", sum_series)
17
VELOCIS EDUCATION PYTHON NOTES
# _____________________________________________________________
"""
1! + 2! + 3! + 4! + ......n!
"""
n = int(input("enter n : "))
total = 0
fact = 1
for i in range(1, n+1):
fact *= i # Indented under for
total += fact # Indented under for
print("sum=", total)
"""
Module 2.6: Array
"""
"""
Write a program to print sum of any 10 numbers using list
"""
print("Enter 10 numbers:")
numbers = [int(input()) for _ in range(10)]
print("Sum =", sum(numbers))
# Sample Output:
# Enter 10 numbers:
#1
#2
#3
#4
#5
#6
#7
#8
#9
# 10
18
VELOCIS EDUCATION PYTHON NOTES
# Sum = 55
# _____________________________________________________________
"""
Write a program to find maximum element from list
"""
# Sample Output:
# How many elements? 5
# Enter 5 elements:
# 12
# 34
# 56
# 78
# 90
# Maximum = 90
# _____________________________________________________________
"""
Write a program to add corresponding elements of two lists and store
them in third list
"""
# Sample Output:
# Enter size of array: 3
# Enter 3 elements of array a:
#1
#2
#3
19
VELOCIS EDUCATION PYTHON NOTES
# Enter 3 elements of array b:
#4
#5
#6
# Third array:
#579
# _____________________________________________________________
"""
Write a program to find number of odd and even elements from the list
"""
# Sample Output:
# How many elements? 5
# Enter 5 elements:
#1
#2
#3
#4
#5
# Even numbers: 2
# Odd numbers: 3
# _____________________________________________________________
"""
Write a program to sort given list in ascending order
"""
20
VELOCIS EDUCATION PYTHON NOTES
# Sample Output:
# How many elements? 5
# Enter 5 elements below:
#3
#1
#4
#2
#5
# Sorted list:
#12345
# _____________________________________________________________
"""
Write a program to sort given list in descending order
"""
# Sample Output:
# How many elements? 5
# Enter 5 elements below:
#3
#1
#4
#2
#5
# Sorted list in descending order:
#5
#4
#3
#2
#1
# _____________________________________________________________
"""
Bubble Sort
"""
21
VELOCIS EDUCATION PYTHON NOTES
# Output:
# Sorted list:
# -9
#5
# 12
# 18
# 36
# _____________________________________________________________
"""
Write a program to add two matrices
"""
# Sample Output:
# Enter 3 x 3 matrix A:
#123
#456
#789
# Enter 3 x 3 matrix B:
22
VELOCIS EDUCATION PYTHON NOTES
#987
#654
#321
# Resultant Matrix C:
# 10 10 10
# 10 10 10
# 10 10 10
# _____________________________________________________________
"""
Write a program to count number of positive, negative and zero
elements from 3 x 3 matrix
"""
# Sample Output:
# Enter 3x3 matrix A:
#123
# -4 -5 6
#000
# Positive Numbers: 4
# Negative Numbers: 2
# Zeroes: 3
# _____________________________________________________________
"""
Read n x n matrix. Print the original matrix and its transpose
"""
n = int(input("Enter n: "))
print(f"Enter {n} x {n} matrix:")
matrix = [[int(input()) for _ in range(n)] for _ in range(n)]
print("Original matrix:")
for row in matrix:
print('\t'.join(map(str, row))) # Indented under for
23
VELOCIS EDUCATION PYTHON NOTES
print("Transpose matrix:")
for i in range(n):
print('\t'.join(str(matrix[j][i]) for j in range(n))) # Indented under for
# Sample Output:
# Enter n: 3
# Enter 3 x 3 matrix:
#123
#456
#789
# Original matrix:
#123
#456
#789
# Transpose matrix:
#147
#258
#369
# _____________________________________________________________
"""
Write a program to check for symmetrical square matrix
"""
n = int(input("Enter n: "))
print(f"Enter {n} x {n} matrix A:")
matrix = [[int(input()) for _ in range(n)] for _ in range(n)]
is_symmetric = all(matrix[i][j] == matrix[j][i] for i in range(n) for j in range(n))
print("Symmetric matrix" if is_symmetric else "Not symmetric matrix")
# Sample Output 1:
# Enter n: 3
# Enter 3 x 3 matrix A:
#123
#245
#356
# Symmetric matrix
# Sample Output 2:
# Enter n : 3
# Enter 3 x 3 matrix A
#123
#234
#456
# Not Symmetric matrix
# _____________________________________________________________
24
VELOCIS EDUCATION PYTHON NOTES
"""
Module 2.7: String
"""
"""
String Length
"""
# Sample Output:
# Enter a string: Hello World
# Length: 11
# _____________________________________________________________
"""
WORD COUNT
"""
# Sample Output:
# Enter a string: Hello World
# Total words: 2
# _____________________________________________________________
"""
Count vowels
"""
# Sample Output:
# Enter a string: Hello World
# Total count: 3
# _____________________________________________________________
25
VELOCIS EDUCATION PYTHON NOTES
"""
Read a string through the keyboard, write a program to print character
by character with the ASCII code
"""
# Sample Output:
# Enter a string: Hello
# H 72
# e 101
# l 108
# l 108
# o 111
# _____________________________________________________________
"""
Read a program to find out the number of times 'a' is there in the
string that is entered through Keyboard
"""
# Sample Output:
# Enter a string: an apple a day keeps the doctor away
# 'a' occurs 5 times in the above string.
# _____________________________________________________________
"""
Find Character
"""
26
VELOCIS EDUCATION PYTHON NOTES
print(f"{c} does not occur in {s}") # Indented under else
# Sample Output:
# Enter original string: Hello World
# Enter character to scan: o
# o occurs at position: 5
# o occurs at position: 8
# _____________________________________________________________
"""
Replace Character
"""
# Sample Output:
# Enter original string: Hello World
# Enter character to replace: o
# Enter new character: x
# Hellx Wxrld
# _____________________________________________________________
"""
Module 2.8: Function
"""
"""
Write a Function to add first n numbers
"""
def addn(m):
return sum(range(1, m+1)) # Indented under def
n = int(input("Enter n: "))
print("Answer =", addn(n))
# Sample Output:
# Enter n: 5
# Answer = 15
27
VELOCIS EDUCATION PYTHON NOTES
# _____________________________________________________________
"""
Write a function to sum of odd numbers between 1 to n where n is
entered through keyboard
"""
def oddsum(m):
return sum(range(1, m+1, 2)) # Indented under def
n = int(input("Enter n: "))
print(f"Sum of odd numbers between 1 to {n} = {oddsum(n)}")
# Sample Output:
# Enter n: 10
# Sum of odd numbers between 1 to 10 = 25
# _____________________________________________________________
"""
Write a function program to sum of square of first n numbers, where n
is entered through keyboard
"""
def squaresum(m):
return sum(i*i for i in range(1, m+1)) # Indented under def
n = int(input("Enter n: "))
print(f"Sum of square numbers from 1 to {n} = {squaresum(n)}")
# Sample Output:
# Enter n: 5
# Sum of square numbers from 1 to 5 = 55
# _____________________________________________________________
"""
Write a function program to find out average of first n numbers, where
n is entered through keyboard
"""
def average(m):
return sum(range(1, m+1)) / m # Indented under def
n = int(input("Enter n: "))
28
VELOCIS EDUCATION PYTHON NOTES
print(f"Average of numbers from 1 to {n} = {average(n):.6f}")
# Sample Output:
# Enter n: 5
# Average of numbers from 1 to 5 = 3.000000
# _____________________________________________________________
"""
Write a function program to find factors of given number n, where n is
entered through keyboard
"""
def factor(m):
return [i for i in range(2, m) if m % i == 0] # Indented under def
n = int(input("Enter n: "))
print(' '.join(map(str, factor(n))))
# Sample Output:
# Enter n: 12
#2346
# _____________________________________________________________
"""
Write a function program to find out factorial of a given number
"""
def factorial(m):
return 1 if m == 0 else m * factorial(m-1) # Indented under def
# Sample Output:
# Enter a number: 5
# Factorial = 120
# _____________________________________________________________
"""
Write a function program to interchange values of two variables (Using
pointers - simulated with mutable objects)
"""
29
VELOCIS EDUCATION PYTHON NOTES
def interchange(a, b):
return b, a # Indented under def
# Sample Output:
# Enter two numbers: 5 10
# a=10 b=5
# _____________________________________________________________
"""
Write a function space(x) that can be used to provide a space of x
positions between two output numbers
"""
def space(x):
print(' ' * x, end='') # Indented under def
print("Line1", end='')
space(10)
print("Line2")
# Sample Output:
# Line1 Line2
# _____________________________________________________________
"""
Write a function to return 1 if the number is prime otherwise return 0
"""
def isprime(m):
if m <= 1:
return 0 # Indented under if
for i in range(2, int(m**0.5)+1):
if m % i == 0:
return 0 # Indented under inner if
return 1 # Indented under def
30
VELOCIS EDUCATION PYTHON NOTES
# Sample Output 1:
# Enter a number to check: 7
# 7 is prime
# Sample Output 2:
# Enter a number to check: 15
# 15 is not prime
# _____________________________________________________________
"""
Write a function power(x,y)
"""
x = float(input("Enter x: "))
y = int(input("Enter y: "))
print(f"{power(x, y):.6f}")
# Sample Output:
# Enter x: 2
# Enter y: 3
# 8.000000
# _____________________________________________________________
"""
Write a function to find out maximum out of three numbers
"""
# Sample Output:
# Enter three numbers: 10 20 15
# Maximum = 20
# _____________________________________________________________
"""
Module 2.9: Structure
31
VELOCIS EDUCATION PYTHON NOTES
"""
"""
Initialization of structure (using class in Python)
"""
class Student:
def __init__(self, rollno, name):
self.rollno = rollno # Indented under __init__
self.name = name # Indented under __init__
s = Student(45, "Bhavesh")
print(f"{s.rollno}\t{s.name}")
# Output:
# 45 Bhavesh
# _____________________________________________________________
"""
Initialization of multiple structures
"""
s1 = Student(45, "Bhavesh")
s2 = Student(65, "Chirag")
print(f"{s1.rollno}\t{s1.name}")
print(f"{s2.rollno}\t{s2.name}")
# Output:
# 45 Bhavesh
# 65 Chirag
# _____________________________________________________________
"""
Reading structure elements from keyboard
"""
32
VELOCIS EDUCATION PYTHON NOTES
print(f"Student #2: {s2.rollno}\t{s2.name}")
# Sample Output:
# Enter rollno and name for first student: 1 John
# Enter rollno and name for second student: 2 Doe
# Student #1: 1 John
# Student #2: 2 Doe
# _____________________________________________________________
"""
Array of structure
"""
class Student:
def __init__(self, rollno, name):
self.rollno = rollno # Indented under __init__
self.name = name # Indented under __init__
# Sample Output:
# How many students? 2
# Student #0: Rollno and name? 1 John
# Student #1: Rollno and name? 2 Doe
# You have entered:
# Student #0: Rollno: 1 Name: John
# Student #1: Rollno: 2 Name: Doe
# _____________________________________________________________
"""
Module 2.10: Pointers
"""
"""
33
VELOCIS EDUCATION PYTHON NOTES
Pointer simulation in Python (using mutable objects)
"""
# Python doesn't have pointers like C, but we can simulate with mutable objects
def modify_value(x):
x[0] = x[0] * 2 # Modifying list element simulates pointer behavior
# Output:
# Before: 5
# After: 10
# _____________________________________________________________
"""
Pointer arithmetic simulation
"""
# Output:
# Current value: 10
# Next value: 20
# _____________________________________________________________
"""
Function returning multiple values (pointer simulation)
"""
def get_values():
return 10, 20, 30 # Returns tuple (immutable)
34
VELOCIS EDUCATION PYTHON NOTES
# Output:
# a=10, b=20, c=30
# _____________________________________________________________
"""
Pass by reference simulation
"""
def modify_list(lst):
lst.append(100) # Modifies original list
numbers = [1, 2, 3]
print("Before:", numbers)
modify_list(numbers)
print("After:", numbers)
# Output:
# Before: [1, 2, 3]
# After: [1, 2, 3, 100]
# _____________________________________________________________
"""
Module 2.11: File Handling
"""
"""
Write to a file
"""
# Output:
# Data written to file successfully.
# _____________________________________________________________
"""
Read from a file
"""
35
VELOCIS EDUCATION PYTHON NOTES
with open("example.txt", "r") as file:
content = file.read() # Indented under with
print("File content:")
print(content)
# Output:
# File content:
# Hello, World!
# This is a file handling example.
# _____________________________________________________________
"""
Append to a file
"""
# Output:
# Data appended to file successfully.
# _____________________________________________________________
"""
Read file line by line
"""
# Output:
# Reading file line by line:
# Hello, World!
# This is a file handling example.
# Appending new line.
# _____________________________________________________________
"""
File existence check
"""
36
VELOCIS EDUCATION PYTHON NOTES
import os
filename = "example.txt"
if os.path.exists(filename):
print(f"{filename} exists") # Indented under if
else:
print(f"{filename} does not exist") # Indented under else
# Output:
# example.txt exists
# _____________________________________________________________
"""
Module 2.12: Exception Handling
"""
"""
Basic try-except block
"""
try:
result = 10 / 0 # Indented under try
except ZeroDivisionError:
print("Cannot divide by zero") # Indented under except
# Output:
# Cannot divide by zero
# _____________________________________________________________
"""
Multiple exceptions
"""
try:
num = int("abc") # Indented under try
except ValueError:
print("Invalid number format") # Indented under except
except Exception as e:
print(f"An error occurred: {e}") # Indented under except
# Output:
# Invalid number format
37
VELOCIS EDUCATION PYTHON NOTES
# _____________________________________________________________
"""
Try-except-else
"""
try:
num = int("123") # Indented under try
except ValueError:
print("Invalid number format") # Indented under except
else:
print(f"Number is: {num}") # Indented under else
# Output:
# Number is: 123
# _____________________________________________________________
"""
Try-except-finally
"""
try:
file = open("nonexistent.txt", "r") # Indented under try
content = file.read() # Indented under try
except FileNotFoundError:
print("File not found") # Indented under except
finally:
print("This always executes") # Indented under finally
# Output:
# File not found
# This always executes
# _____________________________________________________________
"""
Custom exceptions
"""
class CustomError(Exception):
pass # Indented under class
try:
raise CustomError("Something went wrong") # Indented under try
38
VELOCIS EDUCATION PYTHON NOTES
except CustomError as e:
print(f"Custom error: {e}") # Indented under except
# Output:
# Custom error: Something went wrong
# _____________________________________________________________
"""
Module 2.13: Recursion
"""
"""
Factorial using recursion
"""
def factorial(n):
if n == 0 or n == 1: # Indented under def
return 1 # Indented under if
return n * factorial(n-1) # Indented under def
# Output:
# Factorial of 5: 120
# _____________________________________________________________
"""
Fibonacci series using recursion
"""
def fibonacci(n):
if n <= 1: # Indented under def
return n # Indented under if
return fibonacci(n-1) + fibonacci(n-2) # Indented under def
print("Fibonacci sequence:")
for i in range(5): # Indented under for
print(fibonacci(i), end=" ") # Indented under for
# Output:
# Fibonacci sequence:
#01123
# _____________________________________________________________
39
VELOCIS EDUCATION PYTHON NOTES
"""
Sum of digits using recursion
"""
def sum_digits(n):
if n == 0: # Indented under def
return 0 # Indented under if
return n % 10 + sum_digits(n // 10) # Indented under def
# Output:
# Sum of digits in 12345: 15
# _____________________________________________________________
"""
Power calculation using recursion
"""
# Output:
# 2^5 = 32
# _____________________________________________________________
"""
GCD using recursion (Euclidean algorithm)
"""
def gcd(a, b):
if b == 0: # Indented under def
return a # Indented under if
return gcd(b, a % b) # Indented under def
40