Final Record of Python
Final Record of Python
No:01
PROGRAMMING USING VARIABLE ,CONSTANT,
Date: I/O STATEMENT IN PYTHON
AIM:
ALGORITHM:
1. Start
2. Input: Read the user's name.
3. Input: Read the radius of the circle.
4. Calculation:
o Compute the circumference using the formula:
circumference = 2 * pi * radius.
o Compute the area using the formula: area = pi * radius
** 2.
5. Output: Print the user's name.
6. Output: Print the radius of the circle.
7. Output: Print the calculated circumference.
8. Output: Print the calculated area.
9. End
1
SOURCE CODE:
pi=3.14
circumference=2*pi*radius
area=pi*radius*2
print("name:",name)
print("radius:",radius)
print("circumference:",circumference)
print("area:",area)
OUTPUT:
2
enter your name:swathi
name: swathi
radius: 3.56
circumference: 22.3568
area: 22.3568
RESULT:
3
Date:
AIM:
ALGORITHM:
1. Start
2. Arithmetic Operations:
o Initialize num1 to 10 and num2 to 5.
o Compute and display addition, subtraction,
multiplication, division, modulus, exponentiation, and
floor division.
3. Comparison Operations:
o Reinitialize num1 to 10 and num2 to 5.
o Compute and display results of comparison operations:
num1 > num2, num1 < num2, num1 >= num2, num1
<= num2, num1 == num2, and num1 != num2.
4. Logical Operations:
o Initialize is_raining to True and is_sunny to False.
o Compute and display results of logical operations:
is_raining and is_sunny, is_raining or is_sunny, and not
is_sunny.
5. Assignment Operations:
o Initialize x to 10 and y to 5.
o Update x using assignment operators (+=, -=, *=, /=,
%= , **=, and //=) and display the result after each
operation.
6. Bitwise Operations:
o Initialize a to 60 and b to 13.
o Compute and display results of bitwise operations: AND,
OR, XOR, complement, left shift, and right shift.
7. End
4
SOURCE CODE:
# Arithmetic operators
num1= 10
num2= 5
floor_division= num1//num2
print("Addition:", addition)
print("subtraction:", subtraction)
print("subtraction:", subtraction)
print("division:", division)
print("modulus:", modulus)
print("exponentiation:", exponentiation)
#comparison operators
num1=10
5
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
# assignment operators
x= 10
y= 5
x +=y
x *=y
x /=y
x %=y
x **=y
x //=y
#bitwise operators
7
bitwise_and=a & b # binary and
bitwise_or = a| b # binary or
print("bitwise xor:",bitwise_xor)
OUTPUT:
Addition: 15
subtraction: 5
8
subtraction: 5
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
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
bitwise and: 12
bitwise or: 61
9
bitwise xor: 49
RESULT:
Ex.No:03
PROGRAM USING CONDITIONAL STATEMENT
Date:
AIM:
10
To convert temperatures between Fahrenheit and Celsius based
on user input, and handle any errors that may arise from invalid
inputs.
ALGORITHM:
1. Start
2. Input: Read user choice (ch) for conversion type.
3. Check user choice:
o If ch is "F":
Input: Read the Fahrenheit value.
Try to convert the input to a float.
Calculate Celsius using the formula.
Output: Display the result in Celsius.
Catch ValueError: Print an error message if the
input is not numeric.
o Else if ch is "C":
Input: Read the Celsius value.
Try to convert the input to a float.
Calculate Fahrenheit using the formula.
Output: Display the result in Fahrenheit.
Catch ValueError: Print an error message if the
input is not numeric.
o Else:
Output: Print a message indicating the choice is
invalid.
4. End
SOURCE CODE:
11
if ch == "F":
try:
c = 5 / 9 * (f - 32)
except ValueError:
elif ch == "C":
try:
f = (9 / 5 * c) + 32
except ValueError:
else:
OUTPUT:
12
Enter the Celsius value: 56
RESULT:
Ex.No:3
b) PROGRAM USING CONDITIONAL STATEMENT
Date:
AIM:
13
To calculate the total marks and percentage for a student based
on their scores in five subjects, and to assign a grade based on
the calculated percentage.
ALGORITHM:
1. Start
2. Input: Read the marks for five subjects (m1, m2, m3, m4,
m5).
3. Calculate total marks:
o Compute tot_marks = m1 + m2 + m3 + m4 + m5.
4. Calculate percentage:
o Compute percent = tot_marks / 5.
5. Determine grade based on percentage:
o If percent >= 80, set grade to "A".
o Else if percent >= 70, set grade to "B".
o Else if percent >= 60, set grade to "C".
o Else if percent >= 40, set grade to "D".
o Else, set grade to "E".
6. Output: Print tot_marks, percent, and grade.
7. End
SOURCE CODE:
14
print("Please enter the marks for")
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
grade = "A"
grade = "B"
grade = "C"
grade = "D"
else:
grade = "E"
15
# Print results
print("Percentage:", percent)
print("Grade:", grade)
OUTPUT:
Subject 1: 99
Subject 2: 56
Subject 3: 78
16
Subject 4: 89
Subject 5: 59
Percentage: 76.2
Grade: b
RESULT:
Ex.No:4a
) PROGRAM USING WHILE LOOPS
Date:
AIM:
17
ALGORITHM:
1. Start
2. Input: Read the integer n.
3. Check the value of n:
o If n is less than 0:
Print: "No factorial for negative numbers."
o Else if n is equal to 0:
Print: "The factorial for 0 is 1."
o Else (i.e., n is greater than 0):
Initialize f to 1.
Use a for loop to iterate from 1 to n (inclusive):
Multiply f by the current loop variable and
update f.
Print: "The factorial of n is f."
4. End
SOURCE CODE:
if(n<0):
elif(n==0):
18
else:
f=1
i=1
while(i<=n):
f=f*i
i=i+1
OUTPUT:
the factorial of 4 is 24
19
RESULT:
Ex.No:4b
) PROGRAM USING FOR LOOPS
Date:
AIM:
ALGORITHM:
1. Start
2. Input: Read the integer value n from the user.
20
3. Check the value of n:
o If n < 0:
Print: "No factorial for negative numbers."
o Else if n == 0:
Print: "The factorial for 0 is 1."
o Else (i.e., n > 0):
Initialize f to 1.
Use a for loop to iterate from 1 to n (inclusive):
Update f by multiplying it by the current loop
variable i.
Print: "The factorial of n is f."
4. End
SOURCE CODE:
if(n<0):
elif(n==0):
else:
f=1
21
for i in range (1,n+1):
f=f*i
OUTPUT:
the factorial of 4 is 24
22
RESULT:
Ex.No:5a
) PROGRAM USING BREAK STATEMENT
Date:
AIM:
ALGORITHM:
1. Start
2. Input: Use the string "university" for iteration.
3. For each character in the string:
o If the character is "r":
Break the loop.
23
oElse:
Print the character.
4. After the loop ends, print "the end".
5. End
SOURCE CODE:
if val =="r":
break
print(val)
print("the end")
24
OUTPUT:
the end
25
RESULT:
Ex.No:5b
) PROGRAM USING CONTINUE STATEMENT
Date:
AIM:
ALGORITHM:
SOURCE CODE:
if val =="r":
continue
print(val)
print("the end")
27
OUTPUT:
the end
28
RESULT:
Ex.No:5c
) PROGRAM USING PASS STATEMENT
Date:
AIM:
ALGORITHM:
29
SOURCE CODE:
pass
print("the end")
OUTPUT:
the end
30
RESULT:
Ex.No:6a
) PROGRAM USING FUNCTIONS RETURNING
SINGLE VALUE
Date:
AIM:
ALGORITHM:
SOURCE CODE :
def fact(n1):
f=1
f=f*i
return f
fa = fact(n)
32
OUTPUT:
33
RESULT:
AIM:
ALGORITHM:
34
o Prompt the user to input the number of values they wish to enter
(no).
3. Calculate Min and Max:
o Call the minmax function with no as the argument to get the
minimum and maximum values.
4. Print Results:
o Print the minimum and maximum values obtained from the
function.
SOURCE CODE :
def minmax(n):
# Initial input
ma = mi = val
if ma < val:
ma = val
mi = val
35
no = int(input("Enter the number of values: "))
mima = minmax(no)
OUTPUT:
36
RESULT:
Date:
AIM:
ALGORITHM:
SOURCE CODE:
def factorial(n):
if n==0:
return 1
else:
38
OUTPUT:
FACTORIAL- RECURSIVE
factorial of 8 is : 40320
RESULT:
Date:
AIM:
ALGORITHM:
40
o Print Sorted Array: Iterate over the sorted array and
print each element.
SOURCE CODE:
import array
arr_list.sort()
return sorted_arr
#example usage
for i in range(1,n):
sorted_arr=array_sort(arr)
41
print (element, end=" ")
OUTPUT:
RESULT:
42
Ex.No:9 PROGRAM USING STRING-PALINDROME
CHECKING
Date:
AIM:
ALGORITHM:
43
o Print whether the string is a palindrome based on the
function's return value.
SOURCE CODE:
def is_palindrome(string):
length = len(string)
return False
return True
# Example usage
if is_palindrome(input_string):
else:
44
OUTPUT:
RESULT:
45
Thus the program is executed and verified successfully.
Ex.No:10a)
PROGRAM USING BUILT IN MODULES
Date:
AIM:
1. Get the Current Date and Time: It retrieves and prints the
current date and time using Python's datetime module.
2. Generate a Random Number: It generates and prints a
random integer between 1 and 10 using Python's random
module.
3. Calculate the Square Root of a Number: It calculates
and prints the square root of a given number using Python's
math module.
ALGORITHM:
46
o Define a variable number with a value (in this case, 16).
o Use math.sqrt(number) to calculate the square root of
the defined number.
o Print the square root along with a descriptive message.
SOURCE CODE:
import datetime
import random
number = 16
Random number: 5
RESULT:
48
Ex.No:10b
PROGRAM USING USER-DEFINED MODULES
)
Date:
AIM:
ALGORITHM:
49
SOURCE CODE:
def fibo(n):
"""Print Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print() # Print a newline at the end
def fact(n):
"""Return the factorial of n."""
f=1
if n == 0:
return f # 1 is the factorial of 0
else:
for i in range(1, n + 1):
f *= i
return f
OUTPUT:
50
Enter the number to generate Fibonacci series up to:25
RESULT:
51
Date:
AIM:
1. Accessing Elements
2. Slicing.
3. Modifying Elements.
4. Appending Items
5. Removing Items
6. SortingReversing
ALGORITHM:
1. Initialization:
o Define the list fruits with initial values.
2. Access Elements:
o Print the first element of the list (fruits[0]).
o Print the last element of the list using negative indexing
(fruits[-1]).
3. Slicing:
o Extract and print a slice of the list from index 1 to 3 (not
including 3).
4. Modification:
o Change the second element of the list to "blueberry".
o Print the updated list.
5. Appending:
o Add "grape" to the end of the list using the append
method.
o Print the list after appending.
6. Removal:
52
o Remove and print the item at index 2 using the pop
method.
o Print the list after removing the item.
7. Length:
o Print the number of elements in the list using len.
8. Sorting:
o Sort the list alphabetically using the sort method.
o Print the sorted list.
9. Reversing:
o Reverse the order of items in the list using the reverse
method.
o Print the reversed list.
SOURCE CODE:
53
fruits=["apple","banana","cherry","date"]
print("first fruit:",fruits[0])
print("last fruit:",fruits[-1])
print("slice of fruits:",fruits[1:3])
fruits[1]="blueberry"
fruits.append("grape")
removed_fruit=fruits.pop(2)
print("removed fruits:",removed_fruit)
print("number of fruits:",len(fruits))
fruits.sort()
OUTPUT:
number of fruits: 4
RESULT:
55
Date:
AIM:
ALGORITHM:
The algorithm for the operations on the list and tuple involves the
following steps:
1. Initialization:
o Define the list colors with initial values and a tuple
more_colors with additional color values.
2. Access Elements:
o Print the first element of the list (colors[0]).
o Print the last element of the list using negative indexing
(colors[-1]).
3. Slicing:
o Extract and print a slice of the list from index 1 to 3 (not
including 3).
4. Counting Elements:
o Print the number of elements in the list using len.
5. Membership Testing:
o Check if "red" is in the list and print the result.
o Check if "purple" is in the list and print the result.
6. Combining Lists:
o Concatenate colors and more_colors to form a new list
all_colors.
o Print the combined list.
7. Converting Between Types:
o Convert the list colors to a tuple and print it.
o Convert the list colors to a list (this is redundant since
colors is already a list, but demonstrates conversion)
and print it.
56
SOURCE CODE:
color_tuple = tuple(colors_list)
OUTPUT:
no of colors: 4
58
RESULT:
Date:
AIM:
The aim is to demonstrate basic dictionary operations in Python.
59
ALGORITHM:
1. Create a Dictionary:
Initialize a dictionary with some sample data.
2. Access and Print Dictionary Values:
Retrieve and print specific values from the dictionary using
their keys.
3. Update Dictionary Values:
Modify existing values in the dictionary by assigning new
values to specific keys.
4. Add a New Key-Value Pair:
Insert a new key-value pair into the dictionary.
5. Print the Updated Dictionary:
Display the dictionary after adding the new key-value pair.
6. Delete a Key-Value Pair:
Remove a key-value pair from the dictionary using the del
keyword.
7. Check for Key Existence:
Verify whether certain keys exist in the dictionary and print
the result.
8. Retrieve and Print Keys and Values:
Obtain and print all keys and values from the dictionary.
9. Iterate Over the Dictionary:
Loop through the dictionary to print each key-value pair.
SOURCE CODE:
student={
"name":"sujith",
"age":20,
60
"major":"cs",
"gpa":8.9
print("name:",student["name"])
print("age:",student["age"])
print("major:",student["major"])
print("gpa:",student["gpa"])
student["age"]=21
student["gpa"]=8.89
print("updated age:",student["age"])
print("updated gpa:",student["gpa"])
student["year"]="major"
del student["major"]
keys=student.keys()
values= student.values()
print("keys:",keys)
print("values:",values)
OUTPUT:
name: sujith
age: 20
major: cs
gpa: 8.9
updated age: 21
62
updated gpa: 8.89
name: sujith
age: 21
63
RESULT:
Date:
AIM:
The aim of the provided code is to perform basic file operations: writing content to
a file and then reading the content from the file.
ALGORITHM:
64
1. Define Variables:
o Set the file_name to "file.text", which is the name of the
file.
o Define content as "this is some sample text that will be
written to the file.", which will be written to the file.
2. Write Operation:
Use a try block to attempt to open the file in write mode ('w').
SOURCE CODE:
file_name="file.text"
try:
file.write(content)
except IOError as e:
65
print(f"unable to write to the file.{e}")
try:
file_content=file.read()
print("file content:")
print(file_content)
except IOErroe as e:
OUTPUT:
file content:
66
RESULT:
67