Ex no:1 Program using variables, constants, I/O statements in Python.
Program:
# Constants
PI = 3.14159
# Variables
name = input("Enter your name: ")
radius = float(input("Enter the radius of a circle: "))
# Calculations
circumference = 2 * PI * radius
area = PI * radius ** 2
# Output
print("Name:", name)
print("Radius:", radius)
print("Circumference:", circumference)
print("Area:", area)
Output
Enter your name: Chandresh
Enter the radius of a circle: 3.23
Name: Chandresh
Radius: 3.23
Circumference: 20.2946714
Area: 32.775894311
Ex no:2 Program using Operators in Python
Program:
# Arithmetic operators
num1 = 10
num2 = 5
addition = num1 + num2
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
modulus = num1 % num2
exponentiation = num1 ** num2
floor_division = num1 // num2
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulus:", modulus)
print("Exponentiation:", exponentiation)
print("Floor Division:", floor_division)
# Comparison operators
num1 = 10
num2 = 5
print("num1 > num2:", num1 > num2)
print("num1 < num2:", num1 < num2)
print("num1 >= num2:", num1 >= num2)
print("num1 <= num2:", num1 <= num2)
print("num1 == num2:", num1 == num2)
print("num1 != num2:", num1 != num2)
# Logical operators
is_raining = True
is_sunny = False
print("is_raining and is_sunny:", is_raining and is_sunny)
print("is_raining or is_sunny:", is_raining or is_sunny)
print("not is_raining:", not is_raining)
# Assignment operators
x = 10
y=5
x += y
print("x after x += y:", x)
x -= y
print("x after x -= y:", x)
x *= y
print("x after x *= y:", x)
x /= y
print("x after x /= y:", x)
x %= y
print("x after x %= y:", x)
x **= y
print("x after x **= y:", x)
x //= y
print("x after x //= y:", x)
# Bitwise operators
a = 60 # 60 in binary is 00111100
b = 13 # 13 in binary is 00001101
bitwise_and = a & b # Binary AND
bitwise_or = a | b # Binary OR
bitwise_xor = a ^ b # Binary XOR
bitwise_complement = ~a # Binary complement
bitwise_left_shift = a << 2 # Left shift by 2 positions
bitwise_right_shift = a >> 2 # Right shift by 2 positions
print("Bitwise AND:", bitwise_and)
print("Bitwise OR:", bitwise_or)
print("Bitwise XOR:", bitwise_xor)
print("Bitwise complement:", bitwise_complement)
print("Bitwise Left Shift:", bitwise_left_shift)
print("Bitwise Right Shift:", bitwise_right_shift)
Output :
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Modulus: 0
Exponentiation: 100000
Floor Division: 2
num1 > num2: True
num1 < num2: False
num1 >= num2: True
num1 <= num2: False
num1 == num2: False
num1 != num2: True
is_raining and is_sunny: False
is_raining or is_sunny: True
not is_raining: False
x after x += y: 15
x after x -= y: 10
x after x *= y: 50
x after x /= y: 10.0
x after x %= y: 0.0
x after x **= y: 0.0
x after x //= y: 0.0
Bitwise AND: 12
Bitwise OR: 61
Bitwise XOR: 49
Bitwise complement: -61
Bitwise Left Shift: 240
Bitwise Right Shift: 15
Ex no 3:1-Program using Conditional Statements
Program :
#Program to Convert Fahrenheit to Celsius and Vice Versa
ch=input("Enter Your Choice (F-Fahrenheit to Celsius ,
C-Celsius to Fahrenheit)")
if ch=="F" or ch=='f':
f=float(input("Enter the Fahrenheit Value : "))
c=5/9 *(f-32)
print(f,'Fahrenheit equal to ',c,'Celsius')
elif ch=="C" or ch=='c':
c=float(input("Enter the Celsius Value : "))
f=(9/5 *c)+32
print(c,'Celsius equal to ',f,'Fahrenheit')
else:
print("Wrong input. Please Try again.")
Output :
Enter Your Choice (F-Fahrenheit to Celsius ,C-Celsius to Fahrenheit)C
Enter the Celsius Value : 56
56.0 Celsius equal to 132.8 Fahrenheit
Ex no:3 .2-Program using Conditional Statements
# Program used to find the grade of a student
print("Please enter the marks of")
m1=int(input("Subject 1 :"))
m2=int(input("Subject 2 :"))
m3=int(input("Subject 3 :"))
m4=int(input("Subject 4 :"))
m5=int(input("Subject 5 :"))
tot_marks=m1+m2+m3+m4+m5
percent=tot_marks/5
if percent>=80:
grade="A"
elif percent>=70 and percent<80:
grade="B"
elif percent>=60 and percent<70:
grade="B"
elif percent>=40 and percent<60:
grade="B"
else:
grade="E"
print("Total Marks : ",tot_marks)
print("Percentage : ",percent)
print("Grade : ",grade)
Output:
Please enter the marks of
Subject 1 :53
Subject 2 :45
Subject 3 :89
Subject 4 :67
Subject 5 :76
Total Marks : 330
Percentage : 66.0
Grade : B
Ex no:4 Program using Loops
(a). While Loop – Factorial Calculation
Program :
# Program to calculate factorial
n=int(input("Enter a positive integer : "))
if(n<0):
print("No factorial for negative numbers")
elif(n==0):
print("The factorial for 0 is 1")
else:
f=1
i=1
while(i<=n):
f=f*i
i=i+1
print("The factorial of ",n, "is ",f)
Output 1:
Enter a positive integer : 0
The factorial for 0 is 1
Output 2:
Enter a positive integer : 8
The factorial of 8 is 40320
Output 3:
Enter a positive integer : -9
No factorial for negative numbers
(b). For Loop – Factorial Calculation
Program :
# Program to calculate factorial using 'for' loop
n=int(input("Enter a positive integer : "))
if(n<0):
print("No factorial for negative numbers")
elif(n==0):
print("The factorial for 0 is 1")
else:
f=1
for i in range(1,n+1):
f=f*i
print("The factorial of ",n, "is ",f)
Output 1:
Enter a positive integer : 0
The factorial for 0 is 1
Output 2:
Enter a positive integer : 7
The factorial of 7 is 5040
Output 3:
Enter a positive integer : -11
No factorial for negative numbers
Ex no:5 Program using Jump Statements
(a). Break Statement
Program :
# Use of break statement inside the loop
for val in "University":
if val == "r":
break
print(val)
print("The end")
Output :
U
n
i
v
e
The end
(b). Continue Statement
Program :
# Use of continue statement inside the loop
for val in "University":
if val == "r":
continue
print(val)
print("The end")
Output :
U
n
i
v
e
s
i
t
y
The end
(c). Pass Statement
Program :
# Use of pass statement inside the loop
for val in "University":
pass
print("The end")
Output :
The end
Ex no:6 Program using Functions
(a). Function returning single value
Program :
# Program to illustrate find and return factorial value
def fact(n1):
f=1
for i in range(1,n1+1):
f=f*i
return(f)
n=int(input("Enter a positive integer value : "))
fa=fact(n)
print("The factorial value of ",n," is",fa)
Output :
Enter a positive integer value : 6
The factorial value of 6 is 720
(b). Function returning multiple values
Program :
# Program to illustrate multiple return values
def minmax(n):
val=float(input("Enter a value : "))
ma=mi=val
for i in range(1,n):
val=float(input("Enter a value : "))
if ma<val:
ma=val
elif mi>val:
mi=val
return(mi,ma)
no = int(input("Enter 'n' value: "))
mima = minmax(no)
print("Minimum is",mima[0]," Maximum is ",mima[1])
Output :
Enter 'n' value: 6
Enter a value : 12
Enter a value : 32
Enter a value : 43
Enter a value : 54
Enter a value : 654
Enter a value : -34
Minimum is -34.0 Maximum is 654.0
Ex no:7 Program using Recursion
Program :
# Recursive Function - Factorial
def Factorial(n):
if n==0:
return 1
else:
return n * Factorial(n-1) # recursive call
print(format("FACTORIAL - RECURSIVE", '^40'))
n = int (input("Enter number to find factorial : "))
print("Factorial of ", n , " is : ", Factorial(n))
Output :
FACTORIAL - RECURSIVE
Enter number to find factorial : 8
Factorial of 8 is : 40320
Ex no:8 Program using Arrays
Program:
#Program to sort the list of elements using array
import array
def array_sort(arr):
# Convert the array to a list for sorting
arr_list = arr.tolist()
arr_list.sort()
# Convert the sorted list back to an array
sorted_arr = array.array(arr.typecode, arr_list)
return sorted_arr
# Example usage
n=int(input("Enter the number of elements to be sorted : "))
x=float(input("Enter the 0 element : "))
arr = array.array('f', [x])
for i in range(1,n):
str1="Enter the "+str(i)+"th element : "
x=float(input(str1))
arr.append(x)
sorted_arr = array_sort(arr)
# Print the sorted array
for element in sorted_arr:
print(element, end=" ")
Output :
Enter the number of elements to be sorted : 5
Enter the 0 element : 12
Enter the 1th element : 4
Enter the 2th element : -9
Enter the 3th element : 18
Enter the 4th element : 11
-9.0 4.0 11.0 12.0 18.0
Ex no:9 Program using Strings – Palindrome checking
Program:
def is_palindrome(string):
# Remove spaces and convert to lowercase for case-insensitive comparison
string = string.replace(" ", "").lower()
length = len(string)
# Iterate over the characters using a for loop
for i in range(length // 2):
if string[i] != string[(length - 1) - i]:
return False
return True
# Example usage
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The given string '",input_string,"' is a palindrome.")
else:
print("The given string '",input_string,"' is not a palindrome.")
Output 1 :
Enter a string: amma
The given string ' amma ' is a palindrome.
Output 2 :
Enter a string: god
The given string ' god ' is not a palindrome.
Ex no:10 Program using Modules
(a). Built in modules
Program:
import datetime
import random
import math
# Get the current date and time
current_datetime = datetime.datetime.now()
print("Current Date and Time:", current_datetime)
# Generate a random number between 1 and 10
random_number = random.randint(1, 10)
print("Random Number:", random_number)
# Calculate the square root of a number
number = 16
square_root = math.sqrt(number)
print("Square Root of", number, ":", square_root)
Output :
Current Date and Time: 2023-07-15 10:00:49.671686
Random Number: 3
Square Root of 16 : 4.0
(b). User-defined modules
Program:
• User defined Module
# Fibonacci and Factorial module 'myMod.py'
def fibo(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fact(n):
f=1
if(n==0):
return(1)
else:
for i in range(1,n+1):
f=f*i
return(f)
• Main Program
import myMod
n=int(input("Enter the number to generate fibonacci series up to : "))
print("\nFibonacci series upto ' ",n,"' is :")
myMod.fibo(n)
n1=int(input("Enter the n value for factorial : "))
f=myMod.fact(n1)
print("\nThe Factorial for '",n1,"' is :",f)
Output :
Enter the number to generate fibonacci series up to : 25
Fibonacci series upto ' 25 ' is :
0 1 1 2 3 5 8 13 21
Enter the n value for factorial : 6
The Factorial for ' 6 ' is : 720
Ex no:11 Program using Lists
Program:
# Creating a list
fruits = ["apple", "banana", "cherry", "date"]
# Accessing elements
print("First fruit:", fruits[0])
print("Last fruit:", fruits[-1])
print("Slice of fruits:", fruits[1:3])
# Modifying elements
fruits[1] = "blueberry"
print("Modified fruits list:", fruits)
# Adding elements
fruits.append("grape")
print("Fruits list after appending:", fruits)
# Removing elements
removed_fruit = fruits.pop(2)
print("Removed fruit:", removed_fruit)
print("Fruits list after removing:", fruits)
# Length of the list
print("Number of fruits:", len(fruits))
# Sorting the list
fruits.sort()
print("Sorted fruits list:", fruits)
# Reversing the list
fruits.reverse()
print("Reversed fruits list:", fruits)
Output :
First fruit: apple
Last fruit: date
Slice of fruits: ['banana', 'cherry']
Modified fruits list: ['apple', 'blueberry', 'cherry', 'date']
Fruits list after appending: ['apple', 'blueberry', 'cherry', 'date', 'grape']
Removed fruit: cherry
Fruits list after removing: ['apple', 'blueberry', 'date', 'grape']
Number of fruits: 4
Sorted fruits list: ['apple', 'blueberry', 'date', 'grape']
Reversed fruits list: ['grape', 'date', 'blueberry', 'apple']
Ex no:12 Program using Tuples
Program:
# Create a tuple of colors
colors = ("red", "green", "blue", "yellow")
# Accessing elements in the tuple
print("First color:", colors[0])
print("Last color:", colors[-1])
print("Slice of colors:", colors[1:3])
# Counting elements in the tuple
print("Number of colors:", len(colors))
# Checking if an element exists in the tuple
print("Is 'red' in colors?", "red" in colors)
print("Is 'purple' in colors?", "purple" in colors)
# Concatenating tuples
more_colors = ("orange", "purple")
all_colors = colors + more_colors
print("All colors:", all_colors)
# Converting tuple to a list
colors_list = list(colors)
print("Colors as a list:", colors_list)
# Converting list to a tuple
colors_tuple = tuple(colors_list)
print("Colors as a tuple:", colors_tuple)
Output :
First color: red
Last color: yellow
Slice of colors: ('green', 'blue')
Number of colors: 4
Is 'red' in colors? True
Is 'purple' in colors? False
All colors: ('red', 'green', 'blue', 'yellow', 'orange', 'purple')
Colors as a list: ['red', 'green', 'blue', 'yellow']
Colors as a tuple: ('red', 'green', 'blue', 'yellow')
Ex no:13 Program using Dictionaries.
Program:
# Create a dictionary of student information
student = {
"name": "Sujith Kumar",
"age": 20,
"major": "Computer Science",
"gpa": 8.9
}
# Accessing values in the dictionary
print("Name:", student["name"])
print("Age:", student["age"])
print("Major:", student["major"])
print("GPA:", student["gpa"])
# Modifying values in the dictionary
student["age"] = 21
student["gpa"] = 8.89
print("Updated age:", student["age"])
print("Updated GPA:", student["gpa"])
# Adding a new key-value pair to the dictionary
student["year"] = "major"
print("Updated student dictionary:", student)
# Removing a key-value pair from the dictionary
del student["major"]
print("Student dictionary after removing 'major':", student)
# Checking if a key exists in the dictionary
print("Does 'major' exist in the dictionary?", "major" in student)
print("Does 'name' exist in the dictionary?", "name" in student)
# Getting all the keys and values from the dictionary
keys = student.keys()
values = student.values()
print("Keys:", keys)
print("Values:", values)
# Iterating over the dictionary
print("Iterating over the dictionary:")
for key, value in student.items():
print(key + ":", value)
Output :
Name: Sujith Kumar
Age: 20
Major: Computer Science
GPA: 8.9
Updated age: 21
Updated GPA: 8.89
Updated student dictionary: {'name': 'Sujith Kumar', 'age': 21, 'major': 'Computer
Science', 'gpa': 8.89, 'year': 'major'}
Student dictionary after removing 'major': {'name': 'Sujith Kumar', 'age': 21, 'gpa':
8.89, 'year': 'major'}
Does 'major' exist in the dictionary? False
Does 'name' exist in the dictionary? True
Keys: dict_keys(['name', 'age', 'gpa', 'year'])
Values: dict_values(['Sujith Kumar', 21, 8.89, 'major'])
Iterating over the dictionary:
name: Sujith Kumar
age: 21
gpa: 8.89
year: major
Ex no:14 Program for File Handling
Program:
# Writing to a file
file_name = "file.txt"
content = "This is some sample text that will be written to the file."
try:
with open(file_name, 'w') as file:
file.write(content)
print("File write operation completed successfully!")
except IOError as e:
print(f"Unable to write to the file. {e}")
# Reading from a file
try:
with open(file_name, 'r') as file:
file_content = file.read()
print("File read operation completed successfully!")
print("File content:")
print(file_content)
except IOError as e:
print(f"Unable to read the file. {e}")
Output :
File write operation completed successfully!
File read operation completed successfully!
File content:
This is some sample text that will be written to the file.