Python LCA Questions
1) Check if a Number is Even or Odd
Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
Output:
> Enter a number: 23
> 23 is odd.
2) Find the Largest of Three Numbers
Code:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
largest = max(num1, num2, num3)
print(f"The largest number is {largest}.")
Output:
>Enter first number: 24
>Enter second number: 66
>Enter third number: 79
> The largest number is 79
3) Reverse a String
Code:
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"Reversed string: {reversed_string}")
Output:
>Enter a string: I study at MIT
> Reversed string: TIM ta yduts I
4) Check if a Number is Prime
Code:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print(f"{num} is not a prime number.")
break
else:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Output:
> Enter a number: 29
> 29 is a prime number
5) Find the Factorial of a Number
Code:
def factor(n):
if n == 0 or n == 1:
return 1
else:
return n * factor(n - 1)
num = int(input("Enter a number: "))
print(f"The factorial of {num} is {factorial(num)}.")
Output:
> Enter a number: 5
> The factorial of 5 is 120
6) Check if a String is a Palindrome → a string that remains same when its letters are reversed
Code:
string = input("Enter a string: ")
if string == string[::-1]:
print(f'"{string}" is a palindrome.')
else:
print(f'"{string}" is not a palindrome.')
Output:
> Enter a string: level
> level is a palindrome
7) Find the Sum of Digits of a Number
Code:
num = int(input("Enter a number: "))
sum_digits = sum(int(digit) for digit in str(num))
print(f"The sum of digits of {num} is {sum_digits}.")
Output:
> Enter a number: 324
> The sum of digits of 324 is 9
8) Check if Two Strings are Anagrams
Code:
str1 = input("Enter first string: ").lower()
str2 = input("Enter second string: ").lower()
if sorted(str1) == sorted(str2):
print(f'"{str1}" and "{str2}" are anagrams.')
else:
print(f'"{str1}" and "{str2}" are not anagrams.')
Output:
> Enter first string: listen
> Enter second string: silent
> “listen” and “silent” are anagram
9) Print a Right-Angled Triangle Pattern
Code:
rows = int(input("Enter number of rows: "))
for i in range(1, rows + 1):
print("*" * i)
Output:
> Enter a number of rows: 5
*
**
***
****
*****
10) Print a Multiplication Table for a Given Number
Code:
num = int(input("Enter a number: "))
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output:
Enter a number: 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
11) Reverse a number.
Code:
num = int(input("Enter a number: "))
reversed_num = int(str(num)[::-1])
print(f"Reversed number: {reversed_num}")
Output:
> Enter a number: 12345
> Reversed number: 54321
12) Count the Number of Digits in a Number
Code:
num = int(input("Enter a number: "))
num_digits = len(str(num))
print(f"The number of digits in {num} is {num_digits}.")
Output:
> Enter a number: 97652
> The number of digits in 97652 is 5.
13) Convert Temperature from Celsius to Fahrenheit
Code:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F.")
Output:
> Enter temperature in Celsius: 25
> 25.0°C is equal to 77.0°F.
14) Count the Occurrences of a Character in a String
Code:
string = input("Enter a string: ")
char = input("Enter the character to count: ")
count = string.count(char)
print(f ’’The character "{char}" appears {count} times in "{string}".')
Output:
>Enter a string: hello world
>Enter the character to count: l
>The character “l” appears 3 times in “hello world”
15) Check if a Number is Positive, Negative, or Zero.
Code:
num = float(input("Enter a number: "))
if num > 0:
print(f"{num} is positive.")
elif num < 0:
print(f"{num} is negative.")
else:
print(f"{num} is zero.")
Output:
> Enter a number: -7
> -7.0 is negative
16) Convert Kilometres to Miles
Code:
kilometers = float(input("Enter distance in kilometers: "))
miles = kilometers * 0.62
print(f"{kilometers} km is equal to {miles} miles.")
Output:
> Enter distance in kilometers: 5
> 5.0 km is equal to 3.1 miles.
17) Print Even Numbers from 1 to N.
Code:
N = int(input("Enter a number: "))
for i in range(2, N + 1, 2): # Start from 2, increment by 2
print(i, end=" ")
Output:
> Enter a number: 10
> 2 4 6 8 10
18) Count the Number of Digits in a Number
Code:
num = int(input("Enter a number: "))
count = 0
while num > 0:
num //= 10 # Remove the last digit
count += 1 # Increase the count
print(f"The number of digits is {count}.")
Output:
>Enter a number: 255421
>The number of digits is 6.
19) Print the First N Natural Numbers Using a While Loop.
Code:
N = int(input("Enter a number: "))
num = 1
while num <= N:
print(num, end=" ")
num += 1
Output:
>Enter a number: 15
>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
20) Print an Inverted Right-Angled Triangle Pattern
Code:
rows = int(input("Enter number of rows: "))
for i in range(rows, 0, -1): # Start from 'rows' and decrease
print("*" * i)
Output:
Enter number of rows: 5
*****
****
***
**
*
21) Count the Number of Vowels in a String
Code:
string = input("Enter a string: ").lower()
vowels = "aeiou"
count = sum(1 for char in string if char in vowels)
print(f”'The number of vowels in "{string}" is {count}.”)
Output:
>Enter a string: I study at MIT
> The number of vowels in “I study at MIT” is 4.
22) Sum of squares of first n natural numbers.
Code:
N = int(input("Enter a number: "))
sum_squares = sum(i**2 for i in range(1, N + 1))
print(f"The sum of squares of the first {N} natural numbers is {sum_squares}.")
Output:
>Enter a number: 5
> The sum of squares of the first 5 natural numbers is 55.
23) Swap 2 numbers without using a third variable
Code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Output:
Enter first number: 5
Enter second number 10
After swapping: a = 10, b = 5
24) Calculate the area of a circle
Code:
radius = float(input("Enter the radius of the circle: "))
pi = 22/7
area = pi * radius ** 2
print(f"The area of the circle with radius {radius} is {area}.")
Output:
> Enter the radius of the circle: 6
> The area of the circle with radius 6.0 is 113.09724.
25) To check whether the given year is a leap year or not
Code:
year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")
Output:
> Enter a year: 2024
> 2024 is a leap year
26) Find the largest among 3 numbers
Code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
largest = max(a, b, c)
print(f"The largest number is {largest}.")
Output:
> Enter first number: 10
> Enter second number: 25
> Enter third number: 15
> The largest number is 25.
27) Find the factors of a number
Code:
num = int(input("Enter a number: "))
print(f"Factors of {num} are:")
for i in range(1, num + 1):
if num % i == 0:
print(i)
Output:
>Enter a number: 12
>Factors of 12 are:
1
2
3
4
6
12
28) Make a simple calculator using function
Code:
def calculator(x, y, operation):
if operation == '+':
return x + y
elif operation == '-':
return x - y
elif operation == '*':
return x * y
elif operation == '/':
return x / y if y != 0 else "Cannot divide by zero"
else:
return "Invalid operation"
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operation (+, -, *, /): ")
print("Result:", calculator(num1, num2, op))
Output:
> Enter first number: 10
> Enter second number: 5
> Enter operation (+, -, *, /): *
> Result: 50.0
29) Compute the power of the number using a function
Code:
def power(base, exponent):
return base ** exponent
num = float(input("Enter the base number: "))
exp = int(input("Enter the exponent: "))
print(f"{num} raised to the power {exp} is: {power(num, exp)}")
Output:
> Enter the base number: 2
> Enter the exponent: 3
> 2.0 raised to the power 3 is: 8.0
30) Check whether the given number is a perfect number or not
Code:
def is_perfect_number(num):
sum_of_factors = sum(i for i in range(1, num) if num % i == 0)
return sum_of_factors == num
number = int(input("Enter a number: "))
if is_perfect_number(number):
print(f"{number} is a perfect number.")
else:
print(f"{number} is not a perfect number.")
Output:
> Enter a number: 6
> 6 is a perfect number.
31) Remove Duplicates from a List
Code:
def remove_duplicates(lst):
return list(set(lst))
numbers = [1, 2, 3, 4, 2, 3, 5, 6, 1]
unique_numbers = remove_duplicates(numbers)
print("List without duplicates:", unique_numbers)
Output:
> List without duplicates: [1, 2, 3, 4, 5, 6]
32) Find Common Elements Between Two Lists
Code:
def find_common_elements(list1, list2):
return list(set(list1) & set(list2))
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
print("Common elements:", find_common_elements(list1, list2))
Output:
> Common elements: [4, 5]
33) Count Occurrences of an Element in a List
Code:
def count_occurrences(lst, element):
return lst.count(element)
numbers = [1, 2, 3, 4, 2, 3, 5, 6, 2, 3, 4, 2]
target = int(input("Enter the number to count: "))
print(f"{target} appears {count_occurrences(numbers, target)} times in the list.")
Output:
> Enter the number to count: 2
> 2 appears 4 times in the list.
34) Count Occurrences of an Element in a Tuple
Code:
numbers = (1, 2, 3, 4, 2, 3, 5, 6, 2, 3, 4, 2)
target = int(input("Enter the number to count: "))
count = numbers.count(target)
print(f"{target} appears {count} times in the tuple.")
Output:
> Enter the number to count: 2
> 2 appears 4 times in the tuple.
35) Display only the common elements from both the Lists
Code:
def common_elements(list1, list2):
return [item for item in list1 if item in list2]
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8, 9]
print("Common elements:", common_elements(list1, list2))
Output:
> Common elements: [4, 5, 6]
36) Reads a file and counts the number of lines.
Code:
def count_lines(filename):
with open(filename, 'r') as file:
return len(file.readlines())
file_name = "sample.txt"
print(f"Number of lines in '{file_name}': {count_lines(file_name)}")
Output:
(Assuming sample.txt contains 4 lines)
> Number of lines in 'sample.txt': 4
37) Write user input to a file and then read it back.
Code:
# Function to write user input to a file
def write_to_file(filename):
with open(filename, 'w') as file:
user_input = input("Enter text to save in the file: ")
file.write(user_input)
# Function to read the file content
def read_from_file(filename):
with open(filename, 'r') as file:
return file.read()
# Specify the file name
file_name = "user_input.txt"
# Write to file
write_to_file(file_name)
# Read and display content
print("Content in file:", read_from_file(file_name))
Output:
> Enter text to save in the file: Hello, this is a test message!
> Content in file: Hello, this is a test message!
38) Copy the content from one file to the other file.
Code:
# Function to copy content from one file to another
def copy_file(source, destination):
with open(source, 'r') as src_file:
content = src_file.read()
with open(destination, 'w') as dest_file:
dest_file.write(content)
# Specify file names
source_file = "source.txt" # File to read from
destination_file = "destination.txt" # File to copy content to
copy_file(source_file, destination_file)
print(f"Content copied from '{source_file}' to '{destination_file}'.")
Output:
> Content copied from 'source.txt' to 'destination.txt'.
39) Search for a specific word inside a text file.
Code:
# Search for a word in a file
file_name = "sample.txt"
word = input("Enter the word to search: ")
with open(file_name, 'r') as file:
content = file.read()
if word in content:
print(f"'{word}' found in the file.")
else:
print(f"'{word}' not found in the file.")
Output:
> Enter the word to search: Python
> 'Python' found in the file. (if found)
>'Python' not found in the file. (if not found)
40) Reads a file and counts the total number of words.
Code:
# Function to count words in a file
def count_words(filename):
with open(filename, 'r') as file:
content = file.read()
return len(content.split())
file_name = "sample.txt" # Ensure this file exists
print(f"Total number of words in '{file_name}': {count_words(file_name)}")
Output:
(Assuming sample.txt contains Hello world! Python is fun.)
> Total number of words in 'sample.txt': 5
41) Remove Duplicates from a List without Using Set
Code:
# Function to remove duplicates while keeping order
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
# Example list with duplicates
numbers = [1, 2, 3, 4, 2, 3, 5, 6, 1]
print("List without duplicates:", remove_duplicates(numbers))
Output:
> List without duplicates: [1, 2, 3, 4, 5, 6]
42) Division Calculator with Input Validation (Exception Handling)
Code:
# Function for division with exception handling
def divide_numbers():
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"Result: {num1} ÷ {num2} = {result}")
except ValueError:
print("Invalid input! Please enter numeric values.")
except ZeroDivisionError:
print("Error! Division by zero is not allowed.")
divide_numbers()
Output:
> Enter the first number: 10
> Enter the second number: 2
> Result: 10 ÷ 2 = 5.0
43) Raise a custom exception if the entered age is below 18.
Code:
# Define custom exception class
class UnderageError(Exception):
pass
# Function to check age
def check_age(age):
if age < 18:
raise UnderageError("Access denied! Age must be 18 or above.")
else:
print("Access granted.")
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError:
print("Invalid input! Please enter a valid number.")
except UnderageError as e:
print(e)
Output:
> Enter your age: 20
> Access granted.
44) Copy Content from One File to Another
Code:
with open("source.txt", "r") as src, open("destination.txt", "w") as dest:
dest.write(src.read())
print("File copied successfully!")
Output:
> File copied successfully!
45) Append the user input to the file
Code:
with open("user_data.txt", "a") as file:
file.write(input("Enter text to append: ") + "\n")
print("Text appended successfully.")
Output:
> Enter text to append: Hello, Python!
> Hello, Python!