0% found this document useful (0 votes)
2 views40 pages

Python Final

The document contains Python programming notes covering basic expressions, conditional statements, and loops. It includes examples of programs for printing messages, performing arithmetic operations, determining grades, and calculating areas and volumes. Additionally, it demonstrates the use of loops for various calculations and conditions.
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)
2 views40 pages

Python Final

The document contains Python programming notes covering basic expressions, conditional statements, and loops. It includes examples of programs for printing messages, performing arithmetic operations, determining grades, and calculating areas and volumes. Additionally, it demonstrates the use of loops for various calculations and conditions.
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
You are on page 1/ 40

VELOCIS EDUCATION PYTHON NOTES

"""
Module 2.1: Basic Expression Programs
"""

# Hello World
print("hello world")

# Output:
# hello world
# _____________________________________________________________

print("hello world how are you")

# 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
# _____________________________________________________________

print("hello world\t", end="")


print("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)

# Output (if user enters 5):


#5
#5
# _____________________________________________________________

"""
Write a program to read one number and display it (with messages)
"""

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


print("you have entered :", n)

# Output (if user enters 10):


# Enter a number: 10
# You entered: 10
# _____________________________________________________________

"""
Write a program to add two numbers
"""

n1 = int(input("Enter first number: "))


n2 = int(input("Enter second number: "))
sum = n1 + n2
print("Addition =", sum)

# Output (if user enters 25 and 15):


# Enter first number: 25
# Enter second number: 15
# Addition = 40
# _____________________________________________________________

2
VELOCIS EDUCATION PYTHON NOTES
"""
Write a program to multiply two numbers
"""

n1 = int(input("enter first number : "))


n2 = int(input("enter second number : "))
n3 = n1 * n2
print("multiplication =", n3)

# Output (if user enters 10 and 5):


# enter first number : 10
# enter second number : 5
# multiplication = 50
# _____________________________________________________________

"""
Write a program to find area of a rectangle
"""

side1 = int(input("enter one side : "))


side2 = int(input("enter second side : "))
area = side1 * side2
print("area of rectangle =", area)

# Output (if user enters 5 and 8):


# enter one side : 5
# enter second side : 8
# area of rectangle = 40
# _____________________________________________________________

"""
Write a program to find volume of cube
"""

h = int(input("enter height : "))


l = int(input("enter length : "))
b = int(input("enter breadth : "))
v=l*h*b
print("volume of cube =", v)

# Output (if user enters 5, 4, and 3):


# enter height : 5
# enter length : 4

3
VELOCIS EDUCATION PYTHON NOTES
# enter breadth : 3
# volume of cube = 60
# _____________________________________________________________

"""
Write a program to find area of triangle
"""

h = float(input("enter height : "))


b = float(input("enter base : "))
a = h * b * 0.5
print("area of triangle =", a)

# Output (if user enters 6 and 8):


# enter height : 6
# enter base : 8
# area of triangle = 24.0
# _____________________________________________________________

"""
Write a program to calculate simple interest
"""

p = float(input("principal amount : "))


r = float(input("rate of interest : "))
n = float(input("number of years : "))
i = (p * r * n) / 100
print("interest =", i)

# Output (if user enters 1000, 5, and 2):


# principal amount : 1000
# rate of interest : 5
# number of years : 2
# interest = 100.0
# _____________________________________________________________

"""
Write a program to compute Fahrenheit from centigrade
"""

c = float(input("Enter Temperature in Centigrade: "))


f = 1.8 * c + 32
print("Temperature in Fahrenheit =", f)

4
VELOCIS EDUCATION PYTHON NOTES

# Output (if user enters 25):


# Enter Temperature in Centigrade: 25
# Temperature in Fahrenheit = 77.0
# _____________________________________________________________

"""
Write a program to calculate area of circle
"""

r = float(input("enter radius of circle : "))


pi = 3.14
a = pi * r * r
print("area =", a)

# Output (if user enters 5):


# enter radius of circle : 5
# area = 78.5
# _____________________________________________________________

"""
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)
"""

m = int(input("enter marks : "))


if m >= 35:
print("pass") # Indented under if
print("bye")

# Output (if user enters 50):


# enter marks : 50
# pass
# bye
# Output (if user enters 30):
# enter marks : 30
# bye
# _____________________________________________________________

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)
"""

m = int(input("enter marks : "))


if m >= 35:
print("pass") # Indented under if
else:
print("fail") # Indented under else
print("bye")

# Output (if user enters 50):


# enter marks : 50
# pass
# bye
# Output (if user enters 30):
# enter marks : 30
# fail
# bye
# _____________________________________________________________

"""
Write a program to read three numbers from keyboard and find out
maximum out of these three (nested if-else)
"""

a, b, c = map(int, input("Enter three numbers: ").split())


if a > b:
if a > c:
print(a, "is max") # Indented under inner if
else:
print(c, "is max") # Indented under inner else
elif b > c:
print(b, "is max") # Indented under elif
else:
print(c, "is max") # Indented under else

# Output (if user enters 10, 30, 20):


# Enter three numbers: 10 30 20
# 30 is max
# _____________________________________________________________

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
"""

m = int(input("Enter marks: "))


if m >= 80 and m <= 100:
print("Distinction") # Indented under if
elif m >= 60 and m < 80:
print("First class") # Indented under elif
elif m >= 35 and m < 60:
print("Second class") # Indented under elif
elif m >= 0 and m < 35:
print("Fail") # Indented under elif
else:
print("Invalid marks") # Indented under else
print("Have a nice day")

# Output (if user enters 85):


# Enter marks: 85
# Distinction
# Have a nice day
# Output (if user enters 50):
# Enter marks: 50
# Second class
# Have a nice day
# _____________________________________________________________

"""
Write a program that reads a number from 1 to 7 and accordingly it
should display MONDAY To SUNDAY (switch-case)
"""

# Python doesn't have switch-case, so we use if-elif-else or dictionary


day = int(input("Enter day number: "))
days = {

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")

# Output (if user enters 3):


# Enter day number: 3
# Wednesday
# Have a nice day
# Output (if user enters 8):
# Enter day number: 8
# Invalid day number
# Have a nice day
# _____________________________________________________________

"""
Check whether the given number is positive, negative or zero
"""

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


if n > 0:
print(n, "is positive") # Indented under if
elif n < 0:
print(n, "is negative") # Indented under elif
else:
print(n, "is zero") # Indented under else

# Output (if user enters 5):


# Enter any number: 5
# 5 is positive
# Output (if user enters -3):
# Enter any number: -3
# -3 is negative
# Output (if user enters 0):
# Enter any number: 0
# 0 is zero
# _____________________________________________________________

8
VELOCIS EDUCATION PYTHON NOTES

"""
Write a simple calculator (using if...else if)
"""

num1 = float(input("Enter first number : "))


num2 = float(input("Enter second number : "))
op = input("Operation (+ , - , * , /) : ")
if op == '+':
res = num1 + num2 # Indented under if
elif op == '-':
res = num1 - num2 # Indented under elif
elif op == '*':
res = num1 * num2 # Indented under elif
elif op == '/':
res = num1 / num2 # Indented under elif
else:
print("Invalid choice") # Indented under else
res = None # Indented under else
if res is not None:
print("Result :", res) # Indented under if

# Output (if user enters 10, 5, *):


# Enter first number : 10
# Enter second number : 5
# Operation (+ , - , * , /) : *
# Result : 50.0
# _____________________________________________________________

"""
Write a simple calculator (using switch-case)
"""

# Using dictionary as switch-case alternative


num1 = float(input("Enter first number : "))
num2 = float(input("Enter second number : "))
op = input("Operation (+ , - , * , /) : ")
operations = {
'+': lambda x, y: x + y,
'-': lambda x, y: x - y,
'*': lambda x, y: x * y,
'/': lambda x, y: x / y
}

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

# Output (if user enters 10, 5, *):


# Enter first number : 10
# Enter second number : 5
# Operation (+ , - , * , /) : *
# Result : 50.0
# _____________________________________________________________

"""
Write a program to find out given year, which is leap or not.

A leap year is a year which is evenly divisible by 4, but if it is


evenly divisible by 100 then it is not a leap year,
but if it evenly divisible by 400 then it is a leap year.
"""

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


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year") # Indented under if
else:
print(year, "is not a leap year") # Indented under else

# Output (if user enters 2024):


# Enter a year : 2024
# 2024 is a leap year
# Output (if user enters 1986):
# Enter any year : 1986
# 1986 is not leap year
# _____________________________________________________________

10
VELOCIS EDUCATION PYTHON NOTES

"""
Module 2.3: Loops
"""

"""
To read any five number and print the average value
"""

print("Enter five numbers: ", end="")


numbers = list(map(int, input().split()[:5]))
average = sum(numbers) // 5
print("Average =", average)

# Output (if user enters 10 20 30 40 50):


# Enter five numbers: 10 20 30 40 50
# Average = 30
# _____________________________________________________________

"""
Write a program to find out all the numbers divisible by 5 and 7
between 1 to 100
"""

for i in range(1, 101):


if i % 5 == 0 and i % 7 == 0: # Indented under for
print(i) # Indented under if

# Output:
# 35
# 70
# _____________________________________________________________

"""
Find sum of digits of given numbers
"""

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


sum_digits = 0
while num > 0:
sum_digits += num % 10 # Indented under while
num = num // 10 # Indented under while
print("Sum of digits =", sum_digits)

11
VELOCIS EDUCATION PYTHON NOTES

# Output (if user enters 12345):


# Enter a number: 12345
# Sum of digits = 15
# _____________________________________________________________

"""
To Find out the total number of odd digits within the given number and
print the sum of all odd digits
"""

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


sum_odd = 0
while n > 0:
digit = n % 10 # Indented under while
if digit % 2 != 0: # Indented under while
sum_odd += digit # Indented under if
n = n // 10 # Indented under while
print("Addition of odd digits =", sum_odd)

# Output (if user enters 12345):


# Enter the number: 12345
# Addition of odd digits = 9
# _____________________________________________________________

"""
Reverse a number
"""

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


rev = 0
while num > 0:
rev = rev * 10 + num % 10 # Indented under while
num = num // 10 # Indented under while
print("Reverse =", rev)

# Output (if user enters 12345):


# Enter a number: 12345
# Reverse = 54321
# _____________________________________________________________

12
VELOCIS EDUCATION PYTHON NOTES

"""
Find out sum of first and last digit of a given number
"""

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


last = num % 10
while num > 9:
num = num // 10 # Indented under while
first = num
sum_fl = first + last
print("Sum of first and last digits:", sum_fl)

# Output (if user enters 12345):


# Enter a number: 12345
# Sum of first and last digits: 6
# _____________________________________________________________

"""
WAP to find out largest digit in an given integer e.g. 1 2 3 4, 5 is
the greatest
"""

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


max_digit = 0
while num > 0:
digit = num % 10 # Indented under while
if digit > max_digit: # Indented under while
max_digit = digit # Indented under if
num = num // 10 # Indented under while
print("Largest digit =", max_digit)

# Output (if user enters 567231):


# Enter a number: 567231
# Largest digit = 7
# _____________________________________________________________

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)
"""

for i in range(1, 6):


print(f"Enter three marks for student #{i}: ", end="") # Indented under for
marks = list(map(int, input().split()[:3])) # Indented under for
average = sum(marks) // 3 # Indented under for
print("Average =", average) # Indented under for

# 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
"""

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


temp = num
sum_digits = 0
mul_digits = 1
while temp > 0:
digit = temp % 10 # Indented under while
sum_digits += digit # Indented under while
mul_digits *= digit # Indented under while
temp = temp // 10 # Indented under while
if mul_digits == sum_digits: # After while
print("perfect") # Indented under if
else:
print("Not perfect") # Indented under else

# Output (if user enters 123):


# Enter a number: 123
# perfect
# Output (if user enters 356):
# Enter a number: 356
# Not perfect
# _____________________________________________________________

"""
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
"""

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


temp = num
sum_cubes = 0
while temp > 0:
digit = temp % 10 # Indented under while
sum_cubes += digit ** 3 # Indented under while
temp = temp // 10 # Indented under while
if sum_cubes == num: # After while
print("Armstrong") # Indented under if

15
VELOCIS EDUCATION PYTHON NOTES
else:
print("Not Armstrong") # Indented under else

# Output (if user enters 123):


# Enter a number: 123
# 123 is Not Armstrong
# Output (if user enters 153):
# Enter a number: 153
# 153 is Armstrong
# _____________________________________________________________

"""
Module 2.4: Series
"""

"""
1+2+3+......+n
"""

n = int(input("1+2+3+...+n Enter n: "))


sum_series = sum(range(1, n+1))
print("Sum =", sum_series)

# Output (if user enters 5):


# 1+2+3+...+n Enter n: 5
# Sum = 15
# _____________________________________________________________

"""
2+4+6+......+n
"""

n = int(input("2+4+6+...+n enter n : "))


sum_series = sum(range(2, n+1, 2))
print("sum=", sum_series)

# Output (if user enters 10):


# 2+4+6+ . . . +n enter n : 10
# sum=30
# _____________________________________________________________

16
VELOCIS EDUCATION PYTHON NOTES

"""
1+3+5+......+n
"""

n = int(input("1+3+5+...+n enter n : "))


sum_series = sum(range(1, n+1, 2))
print("sum=", sum_series)

# Output (if user enters 7):


# 1+3+5+ . . . +n enter n : 7
# sum=16
# _____________________________________________________________

"""
1^2 + 2^2 + 3^2 + 4^2 ....... +n^2
"""

n = int(input("1^2+2^2+3^2+4^2...+n^2 enter n : "))


sum_series = sum(i*i for i in range(1, n+1))
print("sum=", sum_series)

# Output (if user enters 5):


# 1^2+2^2+3^2+4^2...+n^2 enter n : 5
# sum=55
# _____________________________________________________________

"""
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)

# Output (if user enters 4):


# Enter n : 4
# Sum = 12

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)

# Output (if user enters 5):


# enter n : 5
# sum=153
# _____________________________________________________________

"""
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
"""

n = int(input("How many elements? "))


print(f"Enter {n} elements:")
elements = [int(input()) for _ in range(n)]
print("Maximum =", max(elements))

# 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
"""

n = int(input("Enter size of array: "))


print(f"Enter {n} elements of array a:")
a = [int(input()) for _ in range(n)]
print(f"Enter {n} elements of array b:")
b = [int(input()) for _ in range(n)]
c = [a[i] + b[i] for i in range(n)]
print("Third array:")
print(' '.join(map(str, c)))

# 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
"""

n = int(input("How many elements? "))


print(f"Enter {n} elements:")
numbers = [int(input()) for _ in range(n)]
even = sum(1 for num in numbers if num % 2 == 0)
odd = n - even
print("Even numbers:", even)
print("Odd numbers:", odd)

# 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
"""

n = int(input("How many elements? "))


print(f"Enter {n} elements below:")
numbers = [int(input()) for _ in range(n)]
numbers.sort()
print("Sorted list:")
print(' '.join(map(str, numbers)))

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
"""

n = int(input("How many elements? "))


print(f"Enter {n} elements below:")
numbers = [int(input()) for _ in range(n)]
numbers.sort(reverse=True)
print("Sorted list in descending order:")
for num in numbers:
print(num) # Indented under for

# 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

numbers = [5, -9, 36, 12, 18]


n = len(numbers)
for i in range(n-1):
swapped = False # Indented under for
for j in range(n-i-1): # Indented under for
if numbers[j] > numbers[j+1]: # Indented under inner for
numbers[j], numbers[j+1] = numbers[j+1], numbers[j] # Indented under if
swapped = True # Indented under if
if not swapped: # Indented under outer for
break # Indented under if
print("Sorted list:")
for num in numbers:
print(num) # Indented under for

# Output:
# Sorted list:
# -9
#5
# 12
# 18
# 36
# _____________________________________________________________

"""
Write a program to add two matrices
"""

print("Enter 3 x 3 matrix A:")


a = [[int(input()) for _ in range(3)] for _ in range(3)]
print("Enter 3 x 3 matrix B:")
b = [[int(input()) for _ in range(3)] for _ in range(3)]
c = [[a[i][j] + b[i][j] for j in range(3)] for i in range(3)]
print("Resultant Matrix C:")
for row in c:
print('\t'.join(map(str, row))) # Indented under for

# 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
"""

print("Enter 3x3 matrix A:")


matrix = [[int(input()) for _ in range(3)] for _ in range(3)]
pos = sum(1 for row in matrix for num in row if num > 0)
neg = sum(1 for row in matrix for num in row if num < 0)
zero = 9 - pos - neg
print("Positive Numbers:", pos)
print("Negative Numbers:", neg)
print("Zeroes:", zero)

# 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
"""

s = input("Enter a string: ")


print("Length:", len(s))

# Sample Output:
# Enter a string: Hello World
# Length: 11
# _____________________________________________________________

"""
WORD COUNT
"""

s = input("Enter a string: ")


words = len(s.split())
print("Total words:", words)

# Sample Output:
# Enter a string: Hello World
# Total words: 2
# _____________________________________________________________

"""
Count vowels
"""

s = input("Enter a string: ")


vowels = sum(1 for char in s.lower() if char in 'aeiou')
print("Total 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
"""

s = input("Enter a string: ")


for char in s:
print(f"{char} {ord(char)}") # Indented under for

# 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
"""

s = input("Enter a string: ")


count = s.lower().count('a')
print(f"'a' occurs {count} times in the above string.")

# Sample Output:
# Enter a string: an apple a day keeps the doctor away
# 'a' occurs 5 times in the above string.
# _____________________________________________________________

"""
Find Character
"""

s = input("Enter original string: ")


c = input("Enter character to scan: ")
positions = [i+1 for i, char in enumerate(s) if char == c]
if positions:
for pos in positions:
print(f"{c} occurs at position: {pos}") # Indented under if and for
else:

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
"""

s = input("Enter original string: ")


old_char = input("Enter character to replace: ")
new_char = input("Enter new character: ")
new_s = s.replace(old_char, new_char)
print(new_s)

# 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

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


print(f"Factorial = {factorial(n)}")

# 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

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


b = int(input("Enter second number: "))
a, b = interchange(a, b)
print(f"a={a}\tb={b}")

# 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

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


print(f"{n} is {'prime' if isprime(n) else 'not prime'}")

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)
"""

def power(x, y):


return x ** y # Indented under def

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
"""

def maxthree(a, b, c):


return max(a, b, c) # Indented under def

x, y, z = map(int, input("Enter three numbers: ").split())


print(f"Maximum = {maxthree(x, y, z)}")

# 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
"""

print("Enter rollno and name for first student: ", end="")


roll1, name1 = int(input()), input()
print("Enter rollno and name for second student: ", end="")
roll2, name2 = int(input()), input()
s1 = Student(roll1, name1)
s2 = Student(roll2, name2)
print(f"Student #1: {s1.rollno}\t{s1.name}")

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__

n = int(input("How many students? "))


students = []
for i in range(n):
print(f"Student #{i}: Rollno and name? ", end="")
rollno, name = int(input()), input() # Indented under for
students.append(Student(rollno, name)) # Indented under for

print("You have entered:")


for i, student in enumerate(students):
print(f"Student #{i}: Rollno: {student.rollno} Name: {student.name}") # Indented under for

# 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

value = [5] # Using list as mutable container


print("Before:", value[0])
modify_value(value)
print("After:", value[0])

# Output:
# Before: 5
# After: 10
# _____________________________________________________________

"""
Pointer arithmetic simulation
"""

# Simulating pointer arithmetic with list indices


arr = [10, 20, 30, 40]
index = 0 # Acts like a pointer
print("Current value:", arr[index])
index += 1 # Pointer arithmetic
print("Next value:", arr[index])

# Output:
# Current value: 10
# Next value: 20
# _____________________________________________________________

"""
Function returning multiple values (pointer simulation)
"""

def get_values():
return 10, 20, 30 # Returns tuple (immutable)

a, b, c = get_values() # Multiple assignment simulates pointer behavior


print(f"a={a}, b={b}, c={c}")

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
"""

with open("example.txt", "w") as file:


file.write("Hello, World!\n") # Indented under with
file.write("This is a file handling example.\n") # Indented under with

print("Data written to file successfully.")

# 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
"""

with open("example.txt", "a") as file:


file.write("Appending new line.\n") # Indented under with

print("Data appended to file successfully.")

# Output:
# Data appended to file successfully.
# _____________________________________________________________

"""
Read file line by line
"""

print("Reading file line by line:")


with open("example.txt", "r") as file:
for line in file: # Indented under with
print(line.strip()) # Indented under for

# 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

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

# 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

print("\nSum of digits in 12345:", sum_digits(12345))

# Output:
# Sum of digits in 12345: 15
# _____________________________________________________________

"""
Power calculation using recursion
"""

def power(base, exp):


if exp == 0: # Indented under def
return 1 # Indented under if
return base * power(base, exp-1) # Indented under def

print("2^5 =", power(2, 5))

# 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

print("GCD of 48 and 18:", gcd(48, 18))


# Output:
# GCD of 48 and 18: 6
# _____________________________________________________________

40

You might also like