0% found this document useful (0 votes)
6 views67 pages

Final Record of Python

The document contains multiple programming exercises in Python, including calculating the circumference and area of a circle, demonstrating various operators, converting temperatures, calculating student grades, and factorial computation using loops. Each exercise includes an aim, algorithm, source code, output, and a result indicating successful execution. The programs utilize user input, conditional statements, loops, and error handling.

Uploaded by

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

Final Record of Python

The document contains multiple programming exercises in Python, including calculating the circumference and area of a circle, demonstrating various operators, converting temperatures, calculating student grades, and factorial computation using loops. Each exercise includes an aim, algorithm, source code, output, and a result indicating successful execution. The programs utilize user input, conditional statements, loops, and error handling.

Uploaded by

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

Ex.

No:01
PROGRAMMING USING VARIABLE ,CONSTANT,
Date: I/O STATEMENT IN PYTHON

AIM:

To calculate and display the circumference and area of a circle


based on user-provided radius, and to display the user's name.

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

name=input("enter your name:")

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

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

enter the radius of circle:3.56

name: swathi

radius: 3.56

circumference: 22.3568

area: 22.3568

RESULT:

Thus the program is executed and verified successfully

Ex.No:02 PROGRAM USING OPERATOR IN PYTHON

3
Date:

AIM:

To demonstrate and display the results of different types of


operators in Python, including arithmetic, comparison, logical,
assignment, and bitwise operators.

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

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("subtraction:", subtraction)

print("division:", division)

print("modulus:", modulus)

print("exponentiation:", exponentiation)

print("floor division:", floor_division)

#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

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

# assignment operators

x= 10

y= 5

x +=y

print("x after x += y:", x)


6
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

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

is_raining and is_sunny: False

is_raining or is_sunny: True

Not is_raining: 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

x after x **= y: 0.0

x after x //= y: 0.0

bitwise and: 12

bitwise or: 61
9
bitwise xor: 49

bitwise complement: -61

bitwise left shift: 240

bitwise right shift: 15

RESULT:

Thus the program is executed and verified successfully

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:

# Program to convert Fahrenheit to Celsius and vice versa

# Get user choice

ch = input("Enter your choice (F-Fahrenheit to Celsius, C-Celsius


to Fahrenheit): ").strip().upper()

11
if ch == "F":

# Fahrenheit to Celsius conversion

try:

f = float(input("Enter the Fahrenheit value: "))

c = 5 / 9 * (f - 32)

print(f"{f} Fahrenheit is equal to {c:.2f} Celsius.")

except ValueError:

print("Invalid input. Please enter a numeric value.")

elif ch == "C":

# Celsius to Fahrenheit conversion

try:

c = float(input("Enter the Celsius value: "))

f = (9 / 5 * c) + 32

print(f"{c} Celsius is equal to {f:.2f} Fahrenheit.")

except ValueError:

print("Invalid input. Please enter a numeric value.")

else:

print("Wrong input. Please try again.")

OUTPUT:

Enter your choice (F-Fahrenheit to Celsius, C-Celsius to


Fahrenheit): c

12
Enter the Celsius value: 56

56.0 Celsius is equal to 132.80 Fahrenheit.

RESULT:

Thus the program is executed and verified successfully.

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:

# Program to find the grade of a student

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

# Calculate total marks and percentage

tot_marks = m1 + m2 + m3 + m4 + m5

percent = tot_marks / 5

# Determine grade based on percentage

if percent >= 80:

grade = "A"

elif percent >= 70:

grade = "B"

elif percent >= 60:

grade = "C"

elif percent >= 40:

grade = "D"

else:

grade = "E"

15
# Print results

print("Total marks:", tot_marks)

print("Percentage:", percent)

print("Grade:", grade)

OUTPUT:

Please enter the marks for

Subject 1: 99

Subject 2: 56

Subject 3: 78
16
Subject 4: 89

Subject 5: 59

Total marks: 381

Percentage: 76.2

Grade: b

RESULT:

Thus the program is executed and verified successfully.

Ex.No:4a
) PROGRAM USING WHILE LOOPS

Date:

AIM:

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.

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:

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

18
else:

f=1

i=1

while(i<=n):

f=f*i

i=i+1

print("the factorial of ",n,"is",f)

OUTPUT:

enter a positive integer :4

the factorial of 4 is 24

19
RESULT:

Thus the program is executed and verified successfully.

Ex.No:4b
) PROGRAM USING FOR LOOPS

Date:

AIM:

To calculate the factorial of a positive integer using a for loop and


handle special cases for negative integers and zero.

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:

#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

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

f=f*i

print("the factorial of ",n,"is",f)

OUTPUT:

enter a positive integer :4

the factorial of 4 is 24

22
RESULT:

Thus the program is executed and verified successfully.

Ex.No:5a
) PROGRAM USING BREAK STATEMENT

Date:

AIM:

To iterate through each character in the string "university", print


each character until a specified character is encountered, and
then stop the iteration and print "the end".

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:

for val in "university":

if val =="r":

break

print(val)

print("the end")

24
OUTPUT:

the end

25
RESULT:

Thus the program is executed and verified successfully.

Ex.No:5b
) PROGRAM USING CONTINUE STATEMENT

Date:

AIM:

The aim of the code is to:

1. Iterate through each character in the string "university".


2. Skip printing the character "r" while printing all other
characters.
3. Print "the end" after processing all characters.

ALGORITHM:

1. Initialize the Loop:


o Begin iterating over each character in the string
"university".
2. Character Comparison:
o For each character val in the string:
 Check if the character val is "r".
3. Continue Condition:
26
oIf the character val is "r":
 Skip the rest of the current iteration and continue
with the next character in the loop using the
continue statement.
o If the character val is not "r":
 Print the character.
4. End of Loop:
o After the loop has finished processing all characters
(skipping "r" and printing others), print "the end".

SOURCE CODE:

for val in "university":

if val =="r":

continue

print(val)

print("the end")

27
OUTPUT:

the end

28
RESULT:

Thus the program is executed and verified successfully.

Ex.No:5c
) PROGRAM USING PASS STATEMENT
Date:

AIM:

The aim of the code is to:

1. Iterate over each character in the string "university".


2. Do nothing during each iteration of the loop (thanks to the
pass statement).
3. Print "the end" after the loop completes.

ALGORITHM:

1. Initialize the Loop:


o Begin iterating over each character in the string
"university".
2. Perform No Operation:
o For each character val in the string:
 Execute the pass statement, which does nothing.
3. End of Loop:
o After the loop has finished iterating over all characters
(without performing any actions), print "the end".

29
SOURCE CODE:

for val in "university":

pass

print("the end")

OUTPUT:

the end
30
RESULT:

Thus the program is executed and verified successfully.

Ex.No:6a
) PROGRAM USING FUNCTIONS RETURNING
SINGLE VALUE
Date:

AIM:

The aim of the code is to:

1. Define a function to calculate the factorial of a given positive


integer.
2. Prompt the user to input a positive integer.
3. Calculate the factorial of the provided integer using the
defined function.
4. Print the computed factorial value.

ALGORITHM:

1. Define the Factorial Function:


o Function Name: fact
o Parameters: n1 (the positive integer for which
factorial is to be computed)
o Initialize: Start with a variable f set to 1 (to hold the
computed factorial value).
o Loop: Iterate from 1 to n1 (inclusive) using a for loop.
 For each value i in the loop, update f by
multiplying it with i.
o Return: After the loop completes, return the computed
factorial value f.
2. Input a Positive Integer:
31
o Prompt the user to enter a positive integer value and
store this value in the variable n.
3. Calculate the Factorial:
o Call the fact function with n as the argument to
compute the factorial and store the result in fa.
4. Print the Result:
o Print the computed factorial value along with a
descriptive message.

SOURCE CODE :

# Program to illustrate find and return factorial value

on returning single 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)

32
OUTPUT:

Enter a positive integer value: 6

The factorial value of 6 is 720

33
RESULT:

Thus the program is executed and verified successfully.

Ex.No:6b PROGRAM USING RETURNING MULTIPLE


) VALUE
Date:

AIM:

The aim of the code is to:

1. Define a function that finds the minimum and maximum


values from a specified number of user inputs.
2. Prompt the user to specify how many values they will input.
3. Use the function to compute the minimum and maximum
values from the provided inputs.
4. Print the computed minimum and maximum values.

ALGORITHM:

1. Define the minmax Function:


o Parameters: n (the number of values to be entered).
o Initialize:
 Prompt the user to input the first value.
 Set both ma (maximum) and mi (minimum) to this first
value.
o Loop:
 For each of the remaining n-1 values:
 Prompt the user to input a value.
 Update ma if the new value is greater than the
current maximum.
 Update mi if the new value is less than the current
minimum.
o Return: A tuple containing the minimum and maximum values.
2. Get Number of Values:

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 :

# Program to illustrate multiple return values

def minmax(n):

# Initial input

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)

# Get the number of values to be entered

35
no = int(input("Enter the number of values: "))

mima = minmax(no)

print("Minimum is", mima[0], "Maximum is", mima[1])

OUTPUT:

Enter the number of values: 6

36
RESULT:

Thus the program is executed and verified successfully.

Ex.No:07 PROGRAM USING RECURTION

Date:

AIM:

The aim of the code is to:

1. Define a recursive function to calculate the factorial of a


given number.
2. Prompt the user to input a number.
3. Calculate the factorial of the entered number using the
recursive function.
4. Print the factorial result along with a formatted header.

ALGORITHM:

1. Define the Recursive Factorial Function:


o Function Name: factorial
o Parameters: n (the number for which the factorial is to
be computed).
o Base Case: If n is 0, return 1 (since 0! is 1).
o Recursive Case: For other values of n, return n
multiplied by the factorial of n-1.
2. Print Header:
o Use the format function to print a header message
"FACTORIAL- RECURSIVE" centered in a field of width 40
characters.
3. Input Collection:
o Prompt the user to enter a number and convert it to an
integer.
4. Calculate Factorial:Call the factorial function with the user-
provided number to compute the factorial.
37
5. Print the Result:Print the calculated factorial value along
with a descriptive message.

SOURCE CODE:

def factorial(n):

if n==0:

return 1

else:

return n * factorial (n-1)

print(format("FACTORIAL- RECURSIVE", '^40'))

n=int (input("enter number to find factorial :"))

print("factorial of ",n, " is : ",factorial (n))

38
OUTPUT:

FACTORIAL- RECURSIVE

enter number to find factorial :8

factorial of 8 is : 40320

RESULT:

Thus the program is executed and verified successfully.


39
Ex.No:08 PROGRAM USING ARRAY

Date:

AIM:

The aim of the code is to:

1. Define a function to sort an array of floating-point numbers.


2. Prompt the user to input a number of elements and then
enter each element.
3. Sort the array of elements.
4. Print the sorted array.

ALGORITHM:

1. Define the array_sort Function:


o Parameters: arr (an array object containing the
elements to be sorted).
o Convert Array to List: Convert the array to a list
using toilst() (note: the correct method is tolist()).
o Sort the List: Sort the list using the sort() method.
o Convert Back to Array: Create a new array with the
sorted elements.
o Return: Return the sorted array.
2. Input Collection:
o Number of Elements: Prompt the user to enter the
number of elements to be sorted (n).
o First Element: Prompt the user for the first element
and initialize the array with this value.
o Subsequent Elements: Use a loop to prompt the user
for the remaining n-1 elements and append them to the
array.
3. Sort and Print:
o Call array_sort: Call the array_sort function to get the
sorted array.

40
o Print Sorted Array: Iterate over the sorted array and
print each element.

SOURCE CODE:

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("entet 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:

41
print (element, end=" ")

OUTPUT:

enter the number of elements to be sorted:5

entet the 0 element :12

enter the 1th element :4

4.0 12.0 enter the 2th element :-9

-9.0 4.0 12.0 enter the 3th element :18

-9.0 4.0 12.0 18.0 enter the 4th element :11

-9.0 4.0 11.0 12.0 18.0

RESULT:

Thus the program is executed and verified successfully.

42
Ex.No:9 PROGRAM USING STRING-PALINDROME
CHECKING
Date:

AIM:

The aim of the code is to:

1. Define a function that checks if a given string is a


palindrome.
2. Prompt the user to input a string.
3. Determine if the input string is a palindrome using the
defined function.
4. Print a message indicating whether the string is a
palindrome or not.

ALGORITHM:

1. Define the is_palindrome Function:


o Parameters: string (the string to be checked).
o Preprocessing:
 Remove spaces from the string using replace(" ",
"").
 Convert the string to lowercase using lower() to
ensure case-insensitive comparison.
o Length Calculation: Compute the length of the
processed string.
o Palindrome Check:
 Iterate from 0 to length // 2:
 Compare the character at index i with the
character at index length - 1 - i.
 If any characters differ, return False.
 If all characters match, return True.
2. Input Collection:Prompt the user to enter a string and store
it in input_string.
3. Function Call and Output:Call the is_palindrome function
with input_string.

43
o Print whether the string is a palindrome based on the
function's return value.

SOURCE CODE:

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(f"The given string '{input_string}' is a palindrome.")

else:

print(f"The given string '{input_string}' is not a palindrome.")

44
OUTPUT:

Enter a string: python

The given string 'python' is not a palindrome.

RESULT:
45
Thus the program is executed and verified successfully.

Ex.No:10a)
PROGRAM USING BUILT IN MODULES
Date:

AIM:

The code performs the following tasks:

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:

Here’s a step-by-step explanation of the algorithm used in the


code:

1. Import Required Modules:


o Import datetime to work with dates and times.
o Import random to generate random numbers.
o Import math to perform mathematical operations (in
this case, calculating the square root).
2. Get the Current Date and Time:
o Call datetime.datetime.now() to get the current date
and time.
o Print the current date and time.
3. Generate a Random Number:
o Use random.randint(1, 10) to generate a random
integer between 1 and 10 (both inclusive).
o Print the generated random number.
4. Calculate the Square Root of a Number:

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

import math # Import math for the sqrt function

# Get the current date and time

current_datetime = datetime.datetime.now() # Use now()


method to get the current date and time

print("Current date and time:", current_datetime)

# Generate a random number between 1 and 10

random_number = random.randint(1, 10) # Use randint() method


from the random module

print("Random number:", random_number)

# Calculate the square root of a number

number = 16

square_root = math.sqrt(number) # Use sqrt() method from the


math module

print("Square root of", number, ":", square_root)


47
OUTPUT:

Current date and time: 2024-08-09 12:44:53.394291

Random number: 5

Square root of 16 : 4.0

RESULT:

Thus the program is executed and verified successfully.

48
Ex.No:10b
PROGRAM USING USER-DEFINED MODULES
)
Date:

AIM:

To create a program using modules

ALGORITHM:

Step1:start the program

Step2:Create the User-Defined Module:

 Define a file named math_operations.py containing functions


for addition, subtraction, multiplication, and division.

Step3:Use the User-Defined Module:

 Create another Python file to import and use the functions


from math_operations.py.
 Prompt the user for input and perform the selected
operations using the functions from the module.
 Display the results.

Step4:stop the program

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

Fibonacci series up to’ 25 ’ is:


0 1 1 2 3 5 8 13 21

Enter the n value for factorial: 6

The factorial for ‘ 6 ’ is: 720

RESULT:

Thus the program is executed and verified successfully.

Ex.No:11 PROGRAM USING LIST

51
Date:

AIM:

The aim of the code is to demonstrate various fundamental list


operations in Python, including:

1. Accessing Elements
2. Slicing.
3. Modifying Elements.
4. Appending Items
5. Removing Items
6. SortingReversing

ALGORITHM:

The algorithm involves a sequence of steps to manipulate and


interact with the list fruits. Here is a step-by-step breakdown of
the operations performed:

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"

print("modified fruits list:",fruits)

fruits.append("grape")

print("fruits list after appending:",fruits)

removed_fruit=fruits.pop(2)

print("removed fruits:",removed_fruit)

print("fruits list after removing:",fruits)

print("number of fruits:",len(fruits))

fruits.sort()

print("sorted fruits list:",fruits)

print("reversed fruits list:",fruits)

OUTPUT:

first fruit: apple


54
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 fruits: cherry

fruits list after removing: ['apple', 'blueberry', 'date', 'grape']

number of fruits: 4

sorted fruits list: ['apple', 'blueberry', 'date', 'grape']

reversed fruits list: ['apple', 'blueberry', 'date', 'grape']

RESULT:

Thus the program is executed and verified successfully.

Ex.No:12 PROGRAM USING TUPLE

55
Date:

AIM:

The aim of the code is to demonstrate various operations and


manipulations on lists and tuples in Python

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:

# Define lists and tuples

colors = ["red", "blue", "green", "yellow"]

more_colors = ("orange", "purple")

print("first color:", colors[0])

print("slice of color:", colors[1:3])

print("no of colors:", len(colors))

print("is 'red' in colors?:", "red" in colors)

print("is 'purple' in colors?:", "purple" in colors)

all_colors = colors + list(more_colors)

print("all colors:", all_colors)

colors_list = list(colors) # This is redundant but shows conversion

print("colors as a list:", colors_list)

color_tuple = tuple(colors_list)

print("colors as a tuple:", color_tuple)

OUTPUT:

first color: red


57
last color: yellow

slice of color: ['blue', 'green']

no of colors: 4

is 'red' in colors?: True

is 'purple' in colors?: False

all colors: ['red', 'blue', 'green', 'yellow', 'orange', 'purple']

colors as a list: ['red', 'blue', 'green', 'yellow']

colors as a tuple: ('red', 'blue', 'green', 'yellow')

58
RESULT:

Thus the program is executed and verified successfully.

Ex.No:13 PROGRAM USING DICTIONARIES

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"

print("updated student dict:",student)

del student["major"]

print("student dict after removing 'major':",student)

print("does 'major' exist in the dict?","major"in student)

print("does 'name' exist in the dict?","name"in student)

keys=student.keys()

values= student.values()

print("keys:",keys)

print("values:",values)

print("iterating over the dict:")

for keys,value in student.items():


61
print(keys+":",value)

OUTPUT:

name: sujith

age: 20

major: cs

gpa: 8.9

updated age: 21
62
updated gpa: 8.89

updated student dict: {'name': 'sujith', 'age': 21, 'major': 'cs',


'gpa': 8.89, 'year': 'major'}

student dict after removing 'major': {'name': 'sujith', 'age': 21,


'gpa': 8.89, 'year': 'major'}

does 'major' exist in the dict? False

does 'name' exist in the dict? True

keys: dict_keys(['name', 'age', 'gpa', 'year'])

values: dict_values(['sujith', 21, 8.89, 'major'])

iterating over the dict:

name: sujith

age: 21

63
RESULT:

Thus the program is executed and verified successfully.

Ex.No:14 PROGRAM FOR FILE HANDLING

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').

If successful, write the content to the file.


o
o Print a success message if the write operation is
completed.
o If an IOError occurs during the write operation, catch
the exception and print an error message indicating the
failure.
3. Read Operation:
o Use a try block to attempt to open the file in read mode
('r').
o If successful, read the content from the file.
o Print a success message and display the content read
from the file.
o If an IOError occurs during the read operation, catch the
exception and print an error message indicating the
failure.

SOURCE CODE:

file_name="file.text"

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

except IOError as e:
65
print(f"unable to write to the file.{e}")

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 IOErroe as e:

print(f"unable to read the file. {e}")

OUTPUT:

file write operation compleated succesfully

file read operation completed successfully

file content:

this is some sample text that will be written to the file.

66
RESULT:

Thus the program is executed and verified successfully.

67

You might also like