0% found this document useful (0 votes)
18 views16 pages

Python Lab Manual

The document outlines various Python programming exercises, including calculating sums of digits in alternate positions, generating prime numbers, checking for Armstrong numbers, designing a scientific calculator, and more. Each exercise includes an aim, algorithm, program code, output examples, and results confirming successful execution. The exercises cover a range of topics suitable for learning Python programming.

Uploaded by

ranjana
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)
18 views16 pages

Python Lab Manual

The document outlines various Python programming exercises, including calculating sums of digits in alternate positions, generating prime numbers, checking for Armstrong numbers, designing a scientific calculator, and more. Each exercise includes an aim, algorithm, program code, output examples, and results confirming successful execution. The exercises cover a range of topics suitable for learning Python programming.

Uploaded by

ranjana
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

Common to R 2024 Semester II

Department
CIVIL,ECE,EEE,MECH
Hours/week Credit Total Maximum
Course code Course Name
hours Marks
24AID201 Python Programming 3 0 2 4 75 100
Ex. No:1
Print the sum of the digits of a number in alternative positions
Date:
AIM
To write a Python program to calculate the sum of digits of a given number in alternate positions.
ALGORITHM
1. Start the program.
2. Accept a number from the user.
3. Convert the number to a string for easy traversal of digits.
4. Initialize two sums:
5. sum_even_pos for digits in even positions.
6. sum_odd_pos for digits in odd positions.
7. Loop through the digits:
8. If the index is even, add the digit to sum_even_pos.
9. If the index is odd, add the digit to sum_odd_pos.
10. Display the sums of alternate digits.
11. End the program.
PROGRAM
number = input("Enter a number: ")
sum_even_pos = 0
sum_odd_pos = 0
for index in range(len(number)):
digit = int(number[index])
if index % 2 == 0:
sum_even_pos += digit
else:
sum_odd_pos += digit
print(f"Sum of digits at even positions: {sum_even_pos}")
print(f"Sum of digits at odd positions: {sum_odd_pos}")
Output
Enter a number: 123456
Sum of digits at even positions: 9 # (1 + 3 + 5)
Sum of digits at odd positions: 12 # (2 + 4 + 6)

RESULT
Thus, the Python program to find the sum of digits in alternate positions of a number has been successfully
executed and the desired output is obtained.
Ex. No: 2
Generate prime numbers till the given n value
Date:
AIM
To write a Python program to generate all prime numbers up to a given number n.
ALGORITHM
1. Start the program.
2. Accept the value of n from the user.
3. Loop through numbers from 2 to n.
4. For each number:
5. Check if it is divisible by any number from 2 to its square root.
6. If no divisors are found, it is prime.
7. Print the prime numbers.
8. End the program.

PROGRAM
n = int(input("Enter the value of n: "))
print(f"Prime numbers up to {n} are:")
for number in range(2, n + 1):
is_prime = True
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
print(number, end=" ")
Output
Enter the value of n: 20
Prime numbers up to 20 are:
2 3 5 7 11 13 17 19

RESULT
Thus, the Python program to generate all prime numbers up to a given number n has been successfully executed
and the desired output is obtained.
Ex. No:3
Check whether the given number is an Armstrong number or not
Date:
AIM
To write a Python program to check whether the given number is an Armstrong number or not.
ALGORITHM
1. Start the program.
2. Accept a number from the user.
3. Store the original number in a temporary variable.
4. Count the number of digits in the number.
5. Initialize a variable sum to 0.
6. Extract each digit of the number:
7. Raise the digit to the power of the number of digits.
8. Add the result to sum.
9. Compare the sum with the original number.
10. If equal, the number is an Armstrong number.
11. Else, it is not an Armstrong number.
12. End the program.
PROGRAM
number = int(input("Enter a number: "))
temp = number
sum = 0
num_digits = len(str(number))
while temp > 0:
digit = temp % 10
sum += digit ** num_digits
temp //= 10
if number == sum:
print(f"{number} is an Armstrong number.")
else:
print(f"{number} is not an Armstrong number.")
Output
Enter a number: 153
153 is an Armstrong number.
Enter a number: 123
123 is not an Armstrong number.

RESULT
Thus, the Python program to check whether the given number is an Armstrong number or not has been
successfully executed and the desired output is obtained.
Ex. No:4 Design a scientific calculator(+,-,^,*,/) until the last number is given Input:
Date: 5^3*3+6*7-9-2+3^2 Output: 415
AIM
To write a Python program to design a scientific calculator that evaluates arithmetic expressions containing *+,
-, , /, and ^ operators.
ALGORITHM
1. Start the program.
2. Display available operations to the user.
3. Accept two numbers as input.
4. Accept the operator as input.
5. Perform the operation based on the operator:
+ for addition
- for subtraction
* for multiplication
/ for division
^ for power
6. Display the result.
7. End the program.
PROGRAM
print("Scientific Calculator")
print("Select operation:")
print(" + for Addition")
print(" - for Subtraction")
print(" * for Multiplication")
print(" / for Division")
print(" ^ for Power")
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /, ^): ")
num2 = float(input("Enter second number: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
elif operator == '^':
result = num1 ** num2
else:
result = "Invalid Operator"
print("Result:", result)
Output
Scientific Calculator
Select operation:
+ for Addition
- for Subtraction
* for Multiplication
/ for Division
^ for Power
Enter first number: 5
Enter operator (+, -, *, /, ^): ^
Enter second number: 3
Result: 125.0

RESULT
Thus, the program using a switch-case was successfully implemented to perform arithmetic operations on
integer values. It handled division by zero gracefully and displayed an appropriate error message for invalid choices.
Ex. No:5 Find the second largest number from the given 7 digit number
Date: Input:8740392 Output:9874320
AIM
To write a Python program to find the second largest number that can be formed from the digits of a given 7-digit
number.
ALGORITHM
1. Start the program.
2. Take a 7-digit number as input.
3. Convert the number to a list of its digits.
4. Sort the digits in descending order to get the largest number.
5. Swap the last two digits of the sorted list to create the second largest number.
6. Combine the digits to form the second largest number.
7. Display the second largest number.
8. End the program.
PROGRAM
number = input("Enter a 7-digit number: ")
digits = list(number)
[Link](reverse=True)
largest_number = ''.join(digits)
digits[-1], digits[-2] = digits[-2], digits[-1]
second_largest_number = ''.join(digits)
print("Largest number:", largest_number)
print("Second largest number:", second_largest_number)
Output
Enter a 7-digit number: 8740392
Largest number: 9874320
Second largest number: 9874302

RESULT
Thus, the Python program to find the second largest number formed from the digits of a given 7-digit number
was successfully executed and tested.
Ex. No:6 Perform the swapping of 2 numbers to sort the given array
Date: Input:[5,1,6,7,9,0] Output:[0,1,5,6,7,9]
AIM
To write a Python program to sort a given array by swapping elements.
ALGORITHM
1. Start the program.
2. Take the input array.
3. Compare each element with the others.
4. Swap elements if the current element is greater than the next element.
5. Repeat the process until the array is sorted (using Bubble Sort or similar).
6. Display the sorted array.
7. End the program.
PROGRAM
arr = []
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
print("Sorted array:", arr)
Output
Input:[5,1,6,7,9,0]
Output:[0,1,5,6,7,9]

RESULT
Thus, the Python program to sort the given array by performing swaps was successfully executed and tested.
Ex. No:7
Generate Fibonacci series till n numbers with and without using recursion
Date:
AIM
To write Python programs to generate the Fibonacci series up to n numbers with and without recursion.
ALGORITHM
(i) With Recursion:
1. Start the program
2. Define a recursive function to return the nth Fibonacci number:
3. If n <= 1, return n.
4. Otherwise, return the sum of the previous two Fibonacci numbers.
5. Accept the value of n from the user.
6. Loop from 0 to n - 1 and call the recursive function.
7. Print the Fibonacci series.
8. End the program
(ii) Without Recursion:
1. Start the program
2. Accept the value of n from the user.
3. Initialize two variables a = 0, b = 1.
4. Loop n times:
5. Print a.
6. Update a, b = b, a + b.
7. End the program
PROGRAM
(i) With Recursion:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = int(input("Enter the number of terms: "))
print("Fibonacci series using recursion:")
for i in range(n):
print(fibonacci(i), end=" ")
(ii) Without Recursion:
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci series without recursion:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
Output
Enter the number of terms: 10
Fibonacci series using recursion:
0 1 1 2 3 5 8 13 21 34

Enter the number of terms: 10


Fibonacci series without recursion:
0 1 1 2 3 5 8 13 21 34
RESULT
Thus, the program to Armstrong numbers between two given intervals and check if a given number is prime or not
was execute and verified successfully.
[Link] Capitalize the first letter of the word in a sentence Input: india is a biggest
Date: nation Output: India Is A Biggest Nation
AIM
To write a Python program to capitalize the first letter of each word in a given sentence.
ALGORITHM
1. Start the program.
2. Accept a sentence from the user.
3. Use the title() method or loop through each word and capitalize the first letter.
4. Display the modified sentence.
5. End the program.
PROGRAM
Using title() method:
sentence = input("Enter a sentence: ")
capitalized_sentence = [Link]()
print("Capitalized Sentence:", capitalized_sentence)
Without using title() method (using loop):
sentence = input("Enter a sentence: ")
words = [Link]()
capitalized_words = []
for word in words:
capitalized_words.append(word[0].upper() + word[1:])
capitalized_sentence = " ".join(capitalized_words)
print("Capitalized Sentence:", capitalized_sentence)
Output
Enter a sentence: india is a biggest nation
Capitalized Sentence: India Is A Biggest Nation

RESULT
Thus, the Python program to capitalize the first letter of each word in a sentence has been successfully
executed and the desired output is obtained.
Ex. No:9 Find the largest occurrence of the character in a String using dictionary
Date: Input: Apple Output: p
AIM
To write a Python program to find the character with the highest occurrence (maximum frequency) in a given
string using a dictionary.
ALGORITHM
1. Start the program.
2. Accept a string from the user.
3. Initialize an empty dictionary to store the frequency of each character.
4. Loop through each character in the string:
5. If the character is already in the dictionary, increment its count.
6. Otherwise, add the character to the dictionary with a count of 1.
7. Find the character with the highest frequency in the dictionary.
8. Display the character with the maximum occurrence.
9. End the program.
PROGRAM
string = input("Enter a string: ")
char_count = {}
for char in string:
if char in char_count:
char_count[char] += 1
else:
char_count[char] = 1
max_char = max(char_count, key=char_count.get)
print(f"The character with the highest occurrence is: {max_char}")

Output
Enter a string: Apple
The character with the highest occurrence is: p

RESULT
Thus, the Python program to find the largest occurrence of a character in a string using a dictionary has been
successfully executed and the desired output is obtained.
Ex. No:10 Get an input from the user and save it in a file using write mode. Open the
Date: file in read mode and copy the text from one file to another file
AIM
To write a Python program to get input from the user, save it into a file using write mode, and copy the contents
from that file to another file using read and write operations.
ALGORITHM
1. Start the program.
2. Accept text input from the user.
3. Open [Link] in write mode and write the input to the file.
4. Close the file.
5. Open [Link] in read mode and read the contents.
6. Open [Link] in write mode and write the read content into this file.
7. Close both files.
8. Display a success message.
9. End the program.
PROGRAM
user_input = input("Enter text to save in the file: ")
with open("[Link]", "w") as file1:
[Link](user_input)
with open("[Link]", "r") as file1:
content = [Link]()
with open("[Link]", "w") as file2:
[Link](content)
print("The text has been successfully copied from [Link] to [Link].")

Output
Enter text to save in the file: Python is a powerful programming language.
The text has been successfully copied from [Link] to [Link].
*After execution:
Python is a powerful programming language.
*
[Link] will contain the same content copied from [Link].

RESULT
Thus, the Python program to get user input, save it into a file, and copy the contents from one file to another
has been successfully executed and the desired output is obtained.
Ex. No: 11
Count the number of characters, words and lines in a file
Date:
AIM
To write a Python program to count the total number of characters, words, and lines in a given file.
ALGORITHM
1. Start the program.
2. Open the file in read mode.
3. Initialize variables for counting:
4. line_count = 0
5. word_count = 0
6. char_count = 0
7. Read the file line by line.
8. For each line:
9. Increment line_count.
10. Split the line into words and increment word_count by the number of words.
11. Increment char_count by the number of characters in the line.
12. Close the file.
13. Display the counts of characters, words, and lines.
14. End the program.
PROGRAM
filename = "[Link]"
line_count = 0
word_count = 0
char_count = 0
with open(filename, "r") as file:
for line in file:
line_count += 1
word_count += len([Link]())
char_count += len(line)
print(f"Total number of lines: {line_count}")
print(f"Total number of words: {word_count}")
print(f"Total number of characters: {char_count}")

Output
[Link]:
Python is fun.
It is easy to learn.
Enjoy coding!
Output:
Total number of lines: 3
Total number of words: nine
Total number of characters: 49

RESULT
Thus, the Python program to count the number of characters, words, and lines in a file has been successfully
executed and the desired output is obtained.
Ex. No:12
Print the Student Mark list using Modules
Date:
AIM
To write a Python program using modules to print the student mark list.
ALGORITHM
1. Start the program.
2. Create a module file (e.g., [Link]) with a function to accept student details and calculate total and
average marks.
3. Import the module in the main program.
4. Call the function from the module to display the mark list.
5. End the program.
PROGRAM
Step 1: Create a module file [Link]
def mark_list():
name = input("Enter Student Name: ")
reg_no = input("Enter Register Number: ")
marks = []
subjects = int(input("Enter number of subjects: "))
for i in range(subjects):
mark = int(input(f"Enter mark for subject {i+1}: "))
[Link](mark)
total = sum(marks)
average = total / subjects
print("\n----- Student Mark List -----")
print(f"Name: {name}")
print(f"Register Number: {reg_no}")
for i in range(subjects):
print(f"Subject {i+1} Marks: {marks[i]}")
print(f"Total Marks: {total}")
print(f"Average Marks: {average:.2f}”)
Step 2: Create the main program [Link]
import student
student.mark_list() # [Link]
import student
student.mark_list()
Output
Enter Student Name: John
Enter Register Number: 12345
Enter number of subjects: 3
Enter mark for subject 1: 85
Enter mark for subject 2: 90
Enter mark for subject 3: 78
----- Student Mark List -----
Name: John
Register Number: 12345
Subject 1 Marks: 85
Subject 2 Marks: 90
Subject 3 Marks: 78
Total Marks: 253
Average Marks: 84.33
RESULT
Thus, the Python program using modules to print the student mark list has been successfully executed, and the
desired output is obtained.

You might also like