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

Lab File Py - Answer

The document contains a series of Python programming exercises, each with a specific task such as finding the largest of three numbers, counting vowels in a string, calculating the area of a circle, and more. Each exercise includes a code solution, sample input, and output to demonstrate the functionality. The exercises cover a range of topics including loops, conditionals, functions, and basic data structures.

Uploaded by

unknownemail0107
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 views30 pages

Lab File Py - Answer

The document contains a series of Python programming exercises, each with a specific task such as finding the largest of three numbers, counting vowels in a string, calculating the area of a circle, and more. Each exercise includes a code solution, sample input, and output to demonstrate the functionality. The exercises cover a range of topics including loops, conditionals, functions, and basic data structures.

Uploaded by

unknownemail0107
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

Q.

1 Write a Python program to find the largest of three numbers and check if the largest number is even or
odd.

Answer :

print("Taking Input")
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if num1 >= num2 and num1 >= num3:


largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
print("Output")
print("The largest number is:", largest)

if largest % 2 == 0:
print("The largest number is Even.")
else:
print("The largest number is Odd.")

Output
Taking Input
Enter the first number: 23
Enter the second number: 32
Enter the third number: 55
Output
The largest number is: 55
The largest number is Odd.

Green Is Print Statement


Yellow is given Input

Page 1 of 30
Q.2 Write a Python program to count the number of vowels in a string and reverse the string.

Answer :

print("Taking Input")
str = input("Enter Anything to reverse & count vowel: ")

vowels = "AEIOUaeiou"
count = 0

for char in str :


if char in vowels:
count +=1
print("Output")
print("Total Vowel : ", count)
print("Reversed String is: ", str[::-1])

Output
Taking Input
Enter Anything to reverse & count vowel: Kunal Gupta
Output
Total Vowel : 4
Reversed String is: atpuG lanuK

Green Is Print Statement


Yellow is given Input

Page 2 of 30
Q.3 Write a Python program to find the factorial of a number and check if it is a prime number.

Answer :

print("Taking Input")
num = int(input("Enter a Number: "))
Original = num
fact = 1
while num != 1 :
fact*=num
num-=1
print("Output")
print(fact)

if Original <= 1:
print(f"{Original} is not a prime number.")
else:
is_prime = True
for i in range(2, int(Original**0.5) + 1):
if Original % i == 0:
is_prime = False
break

if is_prime:
print(f"{Original} is a prime number.")
else:
print(f"{Original} is not a prime number.")

Output
Taking Input
Enter a Number: 5
Output
120
5 is a prime number.

Green Is Print Statement


Yellow is given Input

Page 3 of 30
Q.4 Write a Python program to calculate the area of a circle and the perimeter of the same circle.

Answer :

print("Taking Input")
r = int(input("Enter the radius of the circle: "))

area = 3.14 * r * r
perimeter = 2 * 3.14 * r
print("Output")
print(f"Area of the circle is: {area:.2f}")
print(f"The Perimeter of the circle is: {perimeter:.2f}")

Output
Taking Input
Enter the radius of the circle: 25
Output
Area of the circle is: 1962.50
The Perimeter of the circle is: 157.00

Green Is Print Statement


Yellow is given Input

Page 4 of 30
Q.5 Write a Python program to generate the multiplication table of a given number, and find the sum of all
the results in the table.

Answer :

print("Taking Input")
num = int(input("Enter a number to generate its multiplication table: "))

sum_of_answer = 0
print("Output")
print(f"Multiplication Table for {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
sum_of_answer+=(num*i)

print(f"The sum of the digits of {num} is: {sum_of_answer}")

Output
Taking Input
Enter a number to generate its multiplication table: 12
Output
Multiplication Table for 12:
12 x 1 = 12
12 x 2 = 24
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
12 x 7 = 84
12 x 8 = 96
12 x 9 = 108
12 x 10 = 120
The sum of the digits of 12 is: 660
Green Is Print Statement
Yellow is given Input

Page 5 of 30
Q.6 Write a Python program to check if a string is a palindrome and contains only alphabetic characters.

Answer :

print("Taking Input")
str_input = input("Enter a string to check: ")

print("Output")
if str_input == str_input[::-1]:
print("Yes! String is a Palindrome.")
else:
print("No! String is not a Palindrome.")
if not str_input.isalpha():
print("Oo! String doesn't contain only alphabetic characters.")
else:
print("Yes! String contains only alphabetic characters.")

Output
Taking Input
Enter a string to check: Kingison
Output
No! String is not a Palindrome.
Yes! String contains only alphabetic characters.
Green Is Print Statement
Yellow is given Input

Page 6 of 30
Q.7 Write a Python program to convert Celsius to Fahrenheit and check if the temperature is below
freezing point.

Answer :

print("Taking Input")
celsius = float(input("Enter the temperature in Celsius: "))

fahrenheit = (celsius * 9/5) + 32


print("Output")
print(f"The temperature in Fahrenheit is: {fahrenheit:.2f}")

if celsius < 0:
print("The temperature is below freezing point.")
else:
print("The temperature is above freezing point.")

Output
Taking Input
Enter the temperature in Celsius: 25
Output
The temperature in Fahrenheit is: 77.00
The temperature is above freezing point.
Green Is Print Statement
Yellow is given Input

Page 7 of 30
Q.8 Write a Python program to create a simple calculator and also find the GCD of two numbers.

Answer :

print("Taking Input")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")

print("Output")
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
result = "Invalid operation"

print("Result:", result)

def gcd(a, b):


while b:
a, b = b, a % b
return a

gcd_result = gcd(num1, num2)


print("GCD of", num1, "and", num2, "is:", gcd_result)

Output
Taking Input
Enter first number: 26
Enter second number: 62
Enter operation (+, -, *, /): /
Output
Result: 0.41935483870967744
GCD of 26 and 62 is: 2.
Green Is Print Statement
Yellow is given Input

Page 8 of 30
Q.9 Write a Python program to find the Fibonacci series up to a given number and check if a number in the
series is even or odd.

Answer :

print("Taking Input")
num = int(input("Enter a number for Fibonacci series: "))
a, b = 0, 1
print("Output")

print("Fibonacci series:")

while a <= num:


print(a, end=" ")
if a % 2 == 0:
print(f"{a} is even")
else:
print(f"{a} is odd")
a, b = b, a + b

Output
Taking Input
Enter a number for Fibonacci series: 50
Output
Fibonacci series:
0 0 is even
1 1 is odd
1 1 is odd
2 2 is even
3 3 is odd
5 5 is odd
8 8 is even
13 13 is odd
21 21 is odd
34 34 is even.
Green Is Print Statement
Yellow is given Input

Page 9 of 30
Q.10 Write a Python program to count the frequency of words in a string and find the total number of
vowels in the string.

Answer :

print("Taking Input")
str = input("Enter Anything to count vowel and string length: ")

vowels = "AEIOUaeiou"
count = 0

for char in str :


if char in vowels:
count +=1
print("Output")
print("Total Vowel : ", count)
print("Length of String is: ", len(str))

Output
Taking Input
Enter Anything to count vowel and string length: Are you still Coping me >
Output
Total Vowel : 8
Length of String is: 25.
Green Is Print Statement
Yellow is given Input

Page 10 of 30
Q.11 Write a Python program to remove duplicates from a list and sort it in ascending order.

Answer :

print("Taking Input")
lst = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

unique_sorted = sorted(set(lst))
print("Output")
print("List after removing duplicates and sorting:", unique_sorted)

Output
Taking Input
Enter a list of numbers separated by spaces: 12 15 16 22 2 9 12 15 0 1
Output
List after removing duplicates and sorting: [0, 1, 2, 9, 12, 15, 16, 22]
Green Is Print Statement
Yellow is given Input

Page 11 of 30
Q.12 Write a Python program to find the largest number in a list and also its position (index).

Answer :

print("Taking Input")
lst = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

largest = max(lst)
index = [Link](largest)
print("Output")
print("Largest number:", largest)
print("Index of largest number:", index)

Output
Taking Input
Enter a list of numbers separated by spaces: 1 5 9 85 56 56 25 24 25
Output
Largest number: 85
Index of largest number: 3.
Green Is Print Statement
Yellow is given Input

Page 12 of 30
Q.13 Write a Python program to find the number of occurrences of a character in a string and check if the
string contains only digits.

Answer :

print("Taking Input")
string = input("Enter a string: ")
char = input("Enter a character to count: ")

count = [Link](char)
is_digit = [Link]()
print("Output")
print(f"Occurrences of '{char}':", count)
if is_digit:
print("The string contains only digits.")
else:
print("The string does not contain only digits.")

Output
Taking Input
Enter a string: asdffdsgrhggf
Enter a character to count: g
Output
Occurrences of 'g': 3
The string does not contain only digits.
Green Is Print Statement
Yellow is given Input

Page 13 of 30
Q.14 Write a Python program to merge two sorted lists into a single sorted list and remove duplicates.

Answer :

print("Taking Input")
list1 = [int(x) for x in input("Enter the elements of the first sorted list, separated by
spaces: ").split()]
list2 = [int(x) for x in input("Enter the elements of the second sorted list, separated by
spaces: ").split()]
i, j = 0, 0
merged_list = []
print("Output")
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
if list1[i] not in merged_list:
merged_list.append(list1[i])
i += 1
elif list1[i] > list2[j]:
if list2[j] not in merged_list:
merged_list.append(list2[j])
j += 1
else:
if list1[i] not in merged_list:
merged_list.append(list1[i])
i += 1, j += 1

while i < len(list1):


if list1[i] not in merged_list:
merged_list.append(list1[i])
i += 1

while j < len(list2):


if list2[j] not in merged_list:
merged_list.append(list2[j])
j += 1
print("Merged and Sorted List:", merged_list)

Output
Taking Input
Enter the elements of the first sorted list, separated by spaces: 1 2 3 4 5 6 7 8
Enter the elements of the second sorted list, separated by spaces: 1 5 6 8 5 8
Output
Merged and Sorted List: [1, 2, 3, 4, 5, 6, 7, 8]
Green Is Print Statement
Yellow is given Input

Page 14 of 30
Q.15 Write a Python program to print a pyramid pattern of stars and numbers side by side.

Answer :

print("Taking Input")
n = int(input("Enter the number of rows for the pyramid: "))

print("Output")
for i in range(1, n + 1):
print(" " * (n - i) + "*" * i + " " * 3 + " ".join(map(str, range(1, i + 1))))

Output
Taking Input
Enter the number of rows for the pyramid: 8
Output
* 1
** 1 2
*** 1 2 3
**** 1 2 3 4
***** 1 2 3 4 5
****** 1 2 3 4 5 6
******* 1 2 3 4 5 6 7
******** 1 2 3 4 5 6 7 8.
Green Is Print Statement
Yellow is given Input

Page 15 of 30
Q.16 Write a Python program to create a scientific calculator that includes basic arithmetic operations
along with square root and power calculations..

Answer :

import math

print("Taking Input")
num1 = float(input("Enter the first number: "))
operation = input("Enter the operation (+, -, *, /, sqrt, power): ")

if operation == "sqrt":
if num1 >= 0:
print("Output")
print("Result: ", [Link](num1))
else:
print("Square root of negative number is not allowed.")
elif operation == "power":
num2 = float(input("Enter the second number (exponent): "))
print("Output")
print("Result: ", [Link](num1, num2))
elif operation in ['+', '-', '*', '/']:
num2 = float(input("Enter the second number: "))
print("Output")
if operation == "+":
print("Result: ", num1 + num2)
elif operation == "-":
print("Result: ", num1 - num2)
elif operation == "*":
print("Result: ", num1 * num2)
elif operation == "/":
if num2 != 0:
print("Result: ", num1 / num2)
else:
print("Division by zero is not allowed.")
else:
print("Invalid operation.")

Output
Taking Input
Enter the first number: 258
Enter the operation (+, -, *, /, sqrt, power): sqrt
Output
Result: 16.06237840420901
Green Is Print Statement
Yellow is given Input

Page 16 of 30
Q.17 Write a Python program to find the factorial of a number using recursion and check if the result is
even or odd.

Answer :

print("Taking Input")
num = int(input("Enter a number: "))

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

fact = factorial(num)
print("Output")
print("Factorial:", fact)
if fact % 2 == 0:
print("The factorial is Even.")
else:
print("The factorial is Odd.")

Output
Taking Input
Enter a number: 5
Output
Factorial: 120
The factorial is Even.
Green Is Print Statement
Yellow is given Input

Page 17 of 30
Q.18 Write a Python program to sort a list of numbers in ascending order without using the built-in sort()
function and find the median of the sorted list.

Answer :

print("Taking Input")
lst = list(map(int, input("Enter a list of numbers separated by spaces: ").split()))

# Sorting logic
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]

median = lst[len(lst) // 2] if len(lst) % 2 != 0 else (lst[len(lst) // 2 - 1] +


lst[len(lst) // 2]) / 2
print("Output")
print("Sorted list:", lst)
print("Median:", median)

Output
Taking Input
Enter a list of numbers separated by spaces: 1 2 3 4 5 6
Output
Sorted list: [1, 2, 3, 4, 5, 6]
Median: 3.5.
Green Is Print Statement
Yellow is given Input

Page 18 of 30
Q.19 Write a Python program to generate a random password and check if it contains at least one
uppercase letter, one lowercase letter, and one digit.

Answer :

import random
import string

print("Output")
password = ''.join([Link](string.ascii_letters + [Link], k=12))
print("Generated Password:", password)

has_upper = any([Link]() for c in password)


has_lower = any([Link]() for c in password)
has_digit = any([Link]() for c in password)

if has_upper and has_lower and has_digit:


print("The password is valid.")
else:
print("The password is invalid.")

Output
Output
Generated Password: UbTJLSX8bLXZ
The password is valid.
Green Is Print Statement
Yellow is given Input

Page 19 of 30
Q.20 Write a Python program to print a pyramid pattern of stars like this:
Q.20
*
***
*****
*******
Q.21 Write a Python program to reverse a string and count the number of digits in it.
*********

Answer :

n = 5

print("Output")
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))

Output
Output
*
***
*****
*******
*********
Green Is Print Statement
Yellow is given Input

Page 20 of 30
Q.21 Write a Python program to reverse a string and count the number of digits in it.

Answer :

print("Taking Input")
string = input("Enter a string: ")

reversed_string = string[::-1]
digit_count = sum(1 for char in reversed_string if [Link]())

print("Output")
print("Reversed String:", reversed_string)
print("Number of digits:", digit_count)

Output
Taking Input
Enter a string: asdf123
Output
Reversed String: 321fdsa
Number of digits: 3
Green Is Print Statement
Yellow is given Input

Page 21 of 30
Q.22 Write a Python program to check whether a number is an Armstrong number and also find the sum of
its digits.

Answer :

print("Taking Input")
num = int(input("Enter a number: "))

# Checking if the number is an Armstrong number


sum_of_powers = sum(int(digit) ** len(str(num)) for digit in str(num))

# Finding the sum of its digits


sum_of_digits = sum(int(digit) for digit in str(num))

print("Output")
if num == sum_of_powers:
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")

print("Sum of its digits:", sum_of_digits)

Output
Taking Input
Enter a number: 123321
Output
123321 is not an Armstrong number.
Sum of its digits: 12
Green Is Print Statement
Yellow is given Input

Page 22 of 30
Q.23 Write a Python program to print the following pattern of numbers:
Q.23

1
12
123
1234

Answer :

n = 4

print("Output")
for i in range(1, n + 1):
for j in range(1, i + 1):
print(j, end="")
print()

Output
Output
1
12
123
1234
Green Is Print Statement
Yellow is given Input

Page 23 of 30
Q.24 Write a Python program to check whether a string is a palindrome and also count the number of
spaces in it.

Answer :

print("Taking Input")
string = input("Enter a string: ")

reversed_string = string[::-1]
is_palindrome = string == reversed_string
space_count = [Link](" ")

print("Output")
if is_palindrome:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
print("Number of spaces:", space_count)

Output
Taking Input
Enter a string: 1 2 3 4 3 2 1
Output
The string is a palindrome.
Number of spaces: 6
Green Is Print Statement
Yellow is given Input

Page 24 of 30
Q.25 Write a Python program to create a random password generator with uppercase letters, lowercase
letters, digits, and special characters.

Answer :

import random
import string

print("Output")
characters = string.ascii_letters + [Link] + [Link]
password = ''.join([Link](characters, k=12))
print("Generated Password:", password)

Output
Output
Generated Password: 0kG#+ltj?+AD
Green Is Print Statement
Yellow is given Input

Page 25 of 30
Q.26 Write a Python program to count and display the frequency of each word in a given sentence.

Answer :

print("Taking Input")
sentence = input("Enter a sentence: ")

word_list = [Link]()
word_count = {}

for word in word_list:


if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

print("Output")
for word, count in word_count.items():
print(f"{word}: {count}")

Output
Taking Input
Enter a sentence: Are you still coping me ?? Dear Don't Copy me
Output
Are: 1
you: 1
still: 1
coping: 1
me: 2
??: 1
Dear: 1
Don't: 1
Copy: 1
Green Is Print Statement
Yellow is given Input

Page 26 of 30
Q.27 Write a Python program to check if a string is a valid hexadecimal number.

Answer :

print("Taking Input")
hex_string = input("Enter a string: ")

print("Output")
if all(char in "0123456789abcdefABCDEF" for char in hex_string):
print("The string is a valid hexadecimal number.")
else:
print("The string is not a valid hexadecimal number.")

Output
Taking Input
Enter a string: abc123
Output
The string is a valid hexadecimal number.
Green Is Print Statement
Yellow is given Input

Page 27 of 30
Q.28 Write a Python program to reverse the elements of a list without using the built-in reverse() function.

Answer :

print("Taking Input")
n = int(input("Enter the number of elements in the list: "))
lst = []
for i in range(n):
[Link](int(input(f"Enter element {i + 1}: ")))

print("Output")
reversed_list = lst[::-1]
print("Reversed List:", reversed_list)

Output
Taking Input
Enter the number of elements in the list: 4
Enter element 1: 2
Enter element 2: 3
Enter element 3: 3
Enter element 4: 3
Output
Reversed List: [3, 3, 3, 2]
Green Is Print Statement
Yellow is given Input

Page 28 of 30
Q.29 Write a Python program to check if a string contains only uppercase letters.

Answer :

print("Taking Input")
text = input("Enter a string: ")

print("Output")
if [Link]():
print("The string contains only uppercase letters.")
else:
print("The string does not contain only uppercase letters.")

Output
Taking Input
Enter a string: ASDFasdf
Output
The string does not contain only uppercase letters.
Green Is Print Statement
Yellow is given Input

Page 29 of 30
Q.30 Write a Python program to find the intersection of two sorted lists without using any built-in
functions.

Answer :

print("Taking Input")
list1 = [int(x) for x in input("Enter the elements of the first sorted list, separated by
spaces: ").split()]
list2 = [int(x) for x in input("Enter the elements of the second sorted list, separated by
spaces: ").split()]

i, j = 0, 0
intersection = []

print("Output")
while i < len(list1) and j < len(list2):
if list1[i] == list2[j]:
[Link](list1[i])
i += 1
j += 1
elif list1[i] < list2[j]:
i += 1
else:
j += 1

print("Intersection:", intersection)

Output
Taking Input
Enter the elements of the first sorted list, separated by spaces: 1 2 3 4 5 6 7 8 9
Enter the elements of the second sorted list, separated by spaces: 2 3 5 8 12 15 16
Output
Intersection: [2, 3, 5, 8]
Green Is Print Statement
Yellow is given Input

Page 30 of 30

You might also like