0% found this document useful (0 votes)
4 views

Python codes

The document contains a series of programming exercises that cover various topics such as checking number properties, performing arithmetic operations, handling loops, and manipulating strings and lists. Each exercise includes a question, a sample code snippet, and the expected output. The exercises are designed to help users practice and understand fundamental programming concepts.

Uploaded by

dnyaneshwani232
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)
4 views

Python codes

The document contains a series of programming exercises that cover various topics such as checking number properties, performing arithmetic operations, handling loops, and manipulating strings and lists. Each exercise includes a question, a sample code snippet, and the expected output. The exercises are designed to help users practice and understand fundamental programming concepts.

Uploaded by

dnyaneshwani232
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
You are on page 1/ 34

1.

Check if a number is positive


Question: Write a program to check if a number is positive.
num = int(input("Enter a number: ")) # Input: 5
if num > 0:
print("The number is positive.")
Output: The number is positive.

2. Check if a number is even or odd


Question: Write a program to check if a number is even or odd.
num = int(input("Enter a number: ")) # Input: 4
if num % 2 == 0:
print(f"{num} is even.")
else:
print(f"{num} is odd.")
Output: 4 is even.

3. Check if a number is positive, negative, or zero


Question: Write a program to check if a number is positive, negative, or zero.
num = int(input("Enter a number: ")) # Input: -3
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Output: Negative
4. Grading system based on marks
Question: Write a program that assigns grades based on marks.
marks = int(input("Enter marks: ")) # Input: 85
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Fail")
Output: Grade B

5. Pass statement demonstration


Question: Write a program using a pass statement.
num = int(input("Enter a number: ")) # Input: 10
if num > 0:
pass # Does nothing
print("Check complete")
Output: Check complete
6. Break statement in a loop
Question: Write a program to exit a loop when a condition is met.
for i in range(5): # Loop from 0 to 4
if i == 3:
break
print(i)
Output:
0
1
2

7. Continue statement in a loop


Question: Write a program to skip an iteration in a loop.
for i in range(5): # Loop from 0 to 4
if i == 3:
continue
print(i)
Output:
0
1
2
4
8. Simple Addition
Question: Write a program to add two numbers.
a = int(input("Enter first number: ")) # Input: 2
b = int(input("Enter second number: ")) # Input: 3
result = a + b
print(f"Sum: {result}")
Output: Sum: 5

9. Simple Subtraction
Question: Write a program to subtract two numbers.
a = int(input("Enter first number: ")) # Input: 7
b = int(input("Enter second number: ")) # Input: 2
result = a - b
print(f"Difference: {result}")
Output: Difference: 5

10. Area of a Circle


Question: Write a program to calculate the area of a circle.
radius = float(input("Enter the radius of the circle: ")) # Input: 5
area = 3.14159 * radius ** 2
print(f"Area of the circle: {area}")
Output: Area of the circle: 78.53975
11. Area of a Rectangle
Question: Write a program to calculate the area of a rectangle.
length = float(input("Enter the length: ")) # Input: 4
breadth = float(input("Enter the breadth: ")) # Input: 5
area = length * breadth
print(f"Area of the rectangle: {area}")
Output: Area of the rectangle: 20.0

12. Check for Armstrong number


Question: Write a program to check if a number is an Armstrong number.
num = int(input("Enter a number: ")) # Input: 153
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if sum == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")
Output: 153 is an Armstrong number.
13. Check for Palindrome
Question: Write a program to check if a string is a palindrome.
string = input("Enter a string: ") # Input: radar
if string == string[::-1]:
print(f"{string} is a palindrome.")
else:
print(f"{string} is not a palindrome.")
Output: radar is a palindrome.

14. Calculate Factorial


Question: Write a program to calculate the factorial of a number.
num = int(input("Enter a number: ")) # Input: 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num} is {factorial}.")
Output: Factorial of 5 is 120.

16. Reverse a Number


Question: Write a program to reverse a given number.
num = int(input("Enter a number: ")) # Input: 1234
reverse = 0
while num > 0:
digit = num % 10
reverse = reverse * 10 + digit
num //= 10
print(f"Reversed number: {reverse}")
Output: Reversed number: 4321

17. Find Maximum in a List


Question: Write a program to find the maximum element in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
maximum = max(arr)
print(f"Maximum number: {maximum}")
Output: Maximum number: 5

18. Find Minimum in a List


Question: Write a program to find the minimum element in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
minimum = min(arr)
print(f"Minimum number: {minimum}")
Output: Minimum number: 1

19. Sum of Elements in a List


Question: Write a program to calculate the sum of elements in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4
arr = [int(x) for x in arr]
total_sum = sum(arr)
print(f"Sum of the numbers: {total_sum}")
Output: Sum of the numbers: 10
20. Count Vowels in a String
Question: Write a program to count the number of vowels in a string.
string = input("Enter a string: ") # Input: Hello World
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
print(f"Number of vowels: {count}")
Output: Number of vowels: 3

21. Count Consonants in a String


Question: Write a program to count the number of consonants in a string.
string = input("Enter a string: ") # Input: Hello World
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char.isalpha() and char not in vowels:
count += 1
print(f"Number of consonants: {count}")
Output: Number of consonants: 7
22. Calculate Average of Numbers
Question: Write a program to calculate the average of a list of numbers.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
average = sum(arr) / len(arr)
print(f"Average: {average}")
Output: Average: 3.0

23. Find Prime Numbers in a Range


Question: Write a program to find all prime numbers in a given range.
start = int(input("Enter start of range: ")) # Input: 10
end = int(input("Enter end of range: ")) # Input: 20
print("Prime numbers:")
for num in range(start, end + 1):
if num > 1:
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num)
Output:
Prime numbers:
11
13
17
19
24. Create a Simple Menu Using Switch Case (If-elif-else approach)
Question: Write a program to create a simple menu using if-elif statements.
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice = int(input("Enter your choice: ")) # Input: 1
if choice == 1:
a = int(input("Enter first number: ")) # Input: 5
b = int(input("Enter second number: ")) # Input: 3
print(f"Result: {a + b}") # Output: Result: 8
elif choice == 2:
a = int(input("Enter first number: ")) # Input: 5
b = int(input("Enter second number: ")) # Input: 3
print(f"Result: {a - b}")
elif choice == 3:
a = int(input("Enter first number: ")) # Input: 5
b = int(input("Enter second number: ")) # Input: 3
print(f"Result: {a * b}")
elif choice == 4:
a = int(input("Enter first number: ")) # Input: 6
b = int(input("Enter second number: ")) # Input: 2
print(f"Result: {a / b}")
else:
print("Invalid choice")
Output: Result: 8
25. Simple Pattern Printing (Triangle)
Question: Write a program to print a right triangle pattern.
rows = int(input("Enter number of rows: ")) # Input: 5
for i in range(1, rows + 1):
print("*" * i)
Output:
*
**
***
****
*****

26. Simple Pattern Printing (Inverted Triangle)


Question: Write a program to print an inverted right triangle pattern.
rows = int(input("Enter number of rows: ")) # Input: 5
for i in range(rows, 0, -1):
print("*" * i)
Output:
*****
****
***
**
*
27. Check for Leap Year
Question: Write a program to check if a year is a leap year.
year = int(input("Enter a year: ")) # Input: 2020
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: 2020 is a leap year.

28. Reverse a String


Question: Write a program to reverse a given string.
string = input("Enter a string: ") # Input: Hello
reversed_string = string[::-1]
print(f"Reversed string: {reversed_string}")
Output: Reversed string: olleH

29. Find the Length of a String


Question: Write a program to find the length of a string.
string = input("Enter a string: ") # Input: Hello
length = len(string)
print(f"Length of the string: {length}")
Output: Length of the string: 5
30. Count Digits in a Number
Question: Write a program to count the number of digits in a number.
num = int(input("Enter a number: ")) # Input: 12345
count = len(str(num))
print(f"Number of digits: {count}")
Output: Number of digits: 5

31. Generate Multiplication Table


Question: Write a program to generate a multiplication table for a number.
num = int(input("Enter a number: ")) # Input: 3
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output:
3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
32. Sum of Odd Numbers in a Range
Question: Write a program to calculate the sum of odd numbers in a given
range.
start = int(input("Enter start of range: ")) # Input: 1
end = int(input("Enter end of range: ")) # Input: 10
odd_sum = sum(num for num in range(start, end + 1) if num % 2 != 0)
print(f"Sum of odd numbers: {odd_sum}")
Output: Sum of odd numbers: 25

33. Sum of Even Numbers in a Range


Question: Write a program to calculate the sum of even numbers in a given
range.
start = int(input("Enter start of range: ")) # Input: 1
end = int(input("Enter end of range: ")) # Input: 10
even_sum = sum(num for num in range(start, end + 1) if num % 2 == 0)
print(f"Sum of even numbers: {even_sum}")
Output: Sum of even numbers: 30

34. Find GCD of Two Numbers


Question: Write a program to find the GCD of two numbers.
import math
a = int(input("Enter first number: ")) # Input: 54
b = int(input("Enter second number: ")) # Input: 24
gcd = math.gcd(a, b)
print(f"GCD of {a} and {b} is {gcd}.")
Output: GCD of 54 and 24 is 6.
35. Find LCM of Two Numbers
Question: Write a program to find the LCM of two numbers.
import math
a = int(input("Enter first number: ")) # Input: 4
b = int(input("Enter second number: ")) # Input: 6
lcm = abs(a * b) // math.gcd(a, b)
print(f"LCM of {a} and {b} is {lcm}.")
Output: LCM of 4 and 6 is 12.

36. Remove Duplicates from a List


Question: Write a program to remove duplicates from a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 4 4
arr = list(set(arr))
print(f"List after removing duplicates: {arr}")
Output: List after removing duplicates: ['1', '2', '3', '4']

37. Flatten a Nested List


Question: Write a program to flatten a nested list.
nested_list = [[1, 2, 3], [4, 5], [6, 7]] # Input: [[1, 2, 3], [4, 5], [6, 7]]
flat_list = [item for sublist in nested_list for item in sublist]
print(f"Flattened list: {flat_list}")
Output: Flattened list: [1, 2, 3, 4, 5, 6, 7]
38. Sort a List
Question: Write a program to sort a list of numbers.
arr = input("Enter numbers separated by space: ").split() # Input: 3 1 4 2
arr = [int(x) for x in arr]
arr.sort()
print(f"Sorted list: {arr}")
Output: Sorted list: [1, 2, 3, 4]

39. Create a List of Squares


Question: Write a program to create a list of squares of numbers from 1 to N.
n = int(input("Enter N: ")) # Input: 5
squares = [i ** 2 for i in range(1, n + 1)]
print(f"List of squares: {squares}")
Output: List of squares: [1, 4, 9, 16, 25]

40. Merge Two Lists


Question: Write a program to merge two lists.
list1 = input("Enter first list of numbers separated by space: ").split() # Input: 1
2
list2 = input("Enter second list of numbers separated by space: ").split() #
Input: 3 4
merged_list = list1 + list2
print(f"Merged list: {merged_list}")
Output: Merged list: ['1', '2', '3', '4']
41. Count Occurrences of an Element in a List
Question: Write a program to count occurrences of an element in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 4
element = input("Enter the element to count: ") # Input: 2
count = arr.count(element)
print(f"{element} occurs {count} times.")
Output: 2 occurs 2 times.

43. Check if Two Strings are Anagrams


Question: Write a program to check if two strings are anagrams.
str1 = input("Enter first string: ") # Input: listen
str2 = input("Enter second string: ") # Input: silent
if sorted(str1) == sorted(str2):
print(f"{str1} and {str2} are anagrams.")
else:
print(f"{str1} and {str2} are not anagrams.")
Output: listen and silent are anagrams.

44. Create a Dictionary from Two Lists


Question: Write a program to create a dictionary from two lists.
keys = input("Enter keys separated by space: ").split() # Input: a b c
values = input("Enter values separated by space: ").split() # Input: 1 2 3
dictionary = dict(zip(keys, values))
print(f"Created dictionary: {dictionary}")
Output: Created dictionary: {'a': '1', 'b': '2', 'c': '3'}
45. Check if a Word is in a Sentence
Question: Write a program to check if a word is in a given sentence.
sentence = input("Enter a sentence: ") # Input: Python is great
word = input("Enter a word to search: ") # Input: great
if word in sentence:
print(f"{word} is present in the sentence.")
else:
print(f"{word} is not present in the sentence.")
Output: great is present in the sentence.

46. Find the Most Frequent Element in a List


Question: Write a program to find the most frequent element in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 3 3
most_frequent = max(set(arr), key=arr.count)
print(f"The most frequent element is: {most_frequent}")
Output: The most frequent element is: 3

47. Count the Number of Words in a Sentence


Question: Write a program to count the number of words in a sentence.
sentence = input("Enter a sentence: ") # Input: Hello World
word_count = len(sentence.split())
print(f"Number of words: {word_count}")
Output: Number of words: 2
48. Convert Celsius to Fahrenheit
Question: Write a program to convert Celsius to Fahrenheit.
celsius = float(input("Enter temperature in Celsius: ")) # Input: 25
fahrenheit = (celsius * 9/5) + 32
print(f"Temperature in Fahrenheit: {fahrenheit}")
Output: Temperature in Fahrenheit: 77.0

49. Convert Fahrenheit to Celsius


Question: Write a program to convert Fahrenheit to Celsius.
fahrenheit = float(input("Enter temperature in Fahrenheit: ")) # Input: 77
celsius = (fahrenheit - 32) * 5/9
print(f"Temperature in Celsius: {celsius}")
Output: Temperature in Celsius: 25.0

50. Check for Perfect Number


Question: Write a program to check if a number is a perfect number.
num = int(input("Enter a number: ")) # Input: 28
sum_of_divisors = sum(i for i in range(1, num) if num % i == 0)
if sum_of_divisors == num:
print(f"{num} is a perfect number.")
else:
print(f"{num} is not a perfect number.")
Output: 28 is a perfect number.
51. Find Sum of First N Natural Numbers
Question: Write a program to find the sum of first N natural numbers.
n = int(input("Enter N: ")) # Input: 5
sum_n = sum(range(1, n + 1))
print(f"Sum of first {n} natural numbers: {sum_n}")
Output: Sum of first 5 natural numbers: 15

52. Check if a String is Numeric


Question: Write a program to check if a string is numeric.
string = input("Enter a string: ") # Input: 1234
if string.isdigit():
print(f"{string} is numeric.")
else:
print(f"{string} is not numeric.")
Output: 1234 is numeric.

53. Generate Random Number


Question: Write a program to generate a random number between 1 and 100.
import random
random_number = random.randint(1, 100)
print(f"Random number: {random_number}")
Output: Random number: 45 (example output)
54. Create a List of Random Numbers
Question: Write a program to create a list of 10 random numbers.
import random
random_numbers = [random.randint(1, 100) for _ in range(10)]
print(f"List of random numbers: {random_numbers}")
Output: List of random numbers: [32, 47, 58, 91, 16, 5, 78, 29, 49, 66]
(example output)

55. Calculate Compound Interest


Question: Write a program to calculate compound interest.
principal = float(input("Enter principal amount: ")) # Input: 1000
rate = float(input("Enter rate of interest: ")) # Input: 5
time = float(input("Enter time (in years): ")) # Input: 2
amount = principal * (1 + rate / 100) ** time
compound_interest = amount - principal
print(f"Compound Interest: {compound_interest}")
Output: Compound Interest: 102.5

56. Convert Binary to Decimal


Question: Write a program to convert binary to decimal.
binary = input("Enter a binary number: ") # Input: 1010
decimal = int(binary, 2)
print(f"Decimal equivalent: {decimal}")
Output: Decimal equivalent: 10
58. Find the Length of the Longest Word in a Sentence
Question: Write a program to find the length of the longest word in a sentence.
sentence = input("Enter a sentence: ") # Input: The quick brown fox
longest_word = max(sentence.split(), key=len)
print(f"Length of the longest word: {len(longest_word)}")
Output: Length of the longest word: 5

59. Check if All Characters are Alphanumeric


Question: Write a program to check if all characters in a string are
alphanumeric.
string = input("Enter a string: ") # Input: Hello123
if string.isalnum():
print(f"{string} is alphanumeric.")
else:
print(f"{string} is not alphanumeric.")
Output: Hello123 is alphanumeric.

60. Find Unique Elements in a List


Question: Write a program to find unique elements in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 4 4
unique_elements = list(set(arr))
print(f"Unique elements: {unique_elements}")
Output: Unique elements: ['1', '2', '3', '4']
61. Calculate the Area of a Circle
Question: Write a program to calculate the area of a circle.
import math
radius = float(input("Enter the radius: ")) # Input: 5
area = math.pi * (radius ** 2)
print(f"Area of the circle: {area}")
Output: Area of the circle: 78.53981633974483

62. Find the Factorial of a Number


Question: Write a program to find the factorial of a number.
import math
num = int(input("Enter a number: ")) # Input: 5
factorial = math.factorial(num)
print(f"Factorial of {num}: {factorial}")
Output: Factorial of 5: 120

63. Check if a Number is Prime


Question: Write a program to check if a number is prime.
num = int(input("Enter a number: ")) # Input: 17
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: 17 is a prime number.

65. Check for Palindrome


Question: Write a program to check if a string is a palindrome.
string = input("Enter a string: ") # Input: madam
if string == string[::-1]:
print(f"{string} is a palindrome.")
else:
print(f"{string} is not a palindrome.")
Output: madam is a palindrome.

66. Find the Sum of Digits in a Number


Question: Write a program to find the sum of digits in a number.
num = int(input("Enter a number: ")) # Input: 123
sum_of_digits = sum(int(digit) for digit in str(num))
print(f"Sum of digits: {sum_of_digits}")
Output: Sum of digits: 6

68. Create a List of Cubes


Question: Write a program to create a list of cubes of numbers from 1 to N.
n = int(input("Enter N: ")) # Input: 3
cubes = [i ** 3 for i in range(1, n + 1)]
print(f"List of cubes: {cubes}")
Output: List of cubes: [1, 8, 27]
69. Check if a String is a Substring of Another String
Question: Write a program to check if one string is a substring of another.
str1 = input("Enter first string: ") # Input: Hello
str2 = input("Enter second string: ") # Input: Hello World
if str1 in str2:
print(f"{str1} is a substring of {str2}.")
else:
print(f"{str1} is not a substring of {str2}.")
Output: Hello is a substring of Hello World.

71. Find the Maximum Number in a List


Question: Write a program to find the maximum number in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
maximum = max(arr)
print(f"Maximum number: {maximum}")
Output: Maximum number: 5

72. Find the Minimum Number in a List


Question: Write a program to find the minimum number in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
minimum = min(arr)
print(f"Minimum number: {minimum}")
Output: Minimum number: 1
73. Merge Two Dictionaries
Question: Write a program to merge two dictionaries.
dict1 = {'a': 1, 'b': 2} # Input: {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4} # Input: {'c': 3, 'd': 4}
merged_dict = {**dict1, **dict2}
print(f"Merged dictionary: {merged_dict}")
Output: Merged dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

74. Find Common Elements in Two Lists


Question: Write a program to find common elements in two lists.
list1 = input("Enter first list of numbers separated by space: ").split() # Input: 1
23
list2 = input("Enter second list of numbers separated by space: ").split() #
Input: 2 3 4
common_elements = list(set(list1) & set(list2))
print(f"Common elements: {common_elements}")
Output: Common elements: ['2', '3']

75. Count the Frequency of Each Character in a String


Question: Write a program to count the frequency of each character in a string.
from collections import Counter
string = input("Enter a string: ") # Input: Hello
frequency = Counter(string)
print(f"Character frequency: {dict(frequency)}")
Output: Character frequency: {'H': 1, 'e': 1, 'l': 2, 'o': 1}
76. Calculate Simple Interest
Question: Write a program to calculate simple interest.
principal = float(input("Enter principal amount: ")) # Input: 1000
rate = float(input("Enter rate of interest: ")) # Input: 5
time = float(input("Enter time (in years): ")) # Input: 2
simple_interest = (principal * rate * time) / 100
print(f"Simple Interest: {simple_interest}")
Output: Simple Interest: 100.0

77. Calculate Distance Between Two Points


Question: Write a program to calculate the distance between two points in 2D
space.
import math
x1, y1 = map(float, input("Enter coordinates of first point (x1 y1): ").split()) #
Input: 1 2
x2, y2 = map(float, input("Enter coordinates of second point (x2 y2): ").split())
# Input: 4 6
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(f"Distance between points: {distance}")
Output: Distance between points: 5.0

78. Calculate the Area of a Triangle


Question: Write a program to calculate the area of a triangle given its base and
height.
base = float(input("Enter the base of the triangle: ")) # Input: 5
height = float(input("Enter the height of the triangle: ")) # Input: 10
area = (base * height) / 2
print(f"Area of the triangle: {area}")
Output: Area of the triangle: 25.0

79. Calculate the Volume of a Cylinder


Question: Write a program to calculate the volume of a cylinder given its radius
and height.
import math
radius = float(input("Enter the radius of the cylinder: ")) # Input: 5
height = float(input("Enter the height of the cylinder: ")) # Input: 10
volume = math.pi * (radius ** 2) * height
print(f"Volume of the cylinder: {volume}")
Output: Volume of the cylinder: 785.3981633974483

80. Find the GCD of Two Numbers


Question: Write a program to find the GCD of two numbers.
import math
num1 = int(input("Enter first number: ")) # Input: 12
num2 = int(input("Enter second number: ")) # Input: 15
gcd = math.gcd(num1, num2)
print(f"GCD of {num1} and {num2}: {gcd}")
Output: GCD of 12 and 15: 3
82. Remove Duplicates from a List
Question: Write a program to remove duplicates from a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 4 4
unique_arr = list(set(arr))
print(f"List without duplicates: {unique_arr}")
Output: List without duplicates: ['1', '2', '3', '4']

83. Find the Longest Palindrome in a List


Question: Write a program to find the longest palindrome in a list of strings.
words = input("Enter words separated by space: ").split() # Input: madam
racecar level
longest_palindrome = max((word for word in words if word == word[::-1]),
key=len, default=None)
print(f"Longest palindrome: {longest_palindrome}")
Output: Longest palindrome: racecar

84. Count the Number of Digits in a String


Question: Write a program to count the number of digits in a string.
string = input("Enter a string: ") # Input: Hello123
digit_count = sum(char.isdigit() for char in string)
print(f"Number of digits: {digit_count}")
Output: Number of digits: 3
86. Print the Even Numbers from a List
Question: Write a program to print even numbers from a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5 6
even_numbers = [int(num) for num in arr if int(num) % 2 == 0]
print(f"Even numbers: {even_numbers}")
Output: Even numbers: [2, 4, 6]

87. Find the Minimum and Maximum of a List


Question: Write a program to find both minimum and maximum of a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
arr = [int(x) for x in arr]
minimum = min(arr)
maximum = max(arr)
print(f"Minimum number: {minimum}, Maximum number: {maximum}")
Output: Minimum number: 1, Maximum number: 5

88. Create a List of Squares


Question: Write a program to create a list of squares of numbers from 1 to N.
n = int(input("Enter N: ")) # Input: 3
squares = [i ** 2 for i in range(1, n + 1)]
print(f"List of squares: {squares}")
Output: List of squares: [1, 4, 9]
89. Find the Intersection of Two Sets
Question: Write a program to find the intersection of two sets.
set1 = set(input("Enter first set of numbers separated by space: ").split()) #
Input: 1 2 3
set2 = set(input("Enter second set of numbers separated by space: ").split()) #
Input: 2 3 4
intersection = set1 & set2
print(f"Intersection of sets: {intersection}")
Output: Intersection of sets: {'2', '3'}

90. Calculate the Sum of Odd Numbers in a List


Question: Write a program to calculate the sum of odd numbers in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 3 4 5
odd_sum = sum(int(num) for num in arr if int(num) % 2 != 0)
print(f"Sum of odd numbers: {odd_sum}")
Output: Sum of odd numbers: 9

91. Count the Number of Words with More Than Three Letters
Question: Write a program to count words with more than three letters in a
sentence.
sentence = input("Enter a sentence: ") # Input: The quick brown fox
word_count = sum(1 for word in sentence.split() if len(word) > 3)
print(f"Number of words with more than three letters: {word_count}")
Output: Number of words with more than three letters: 3
92. Create a Countdown Timer
Question: Write a program to create a simple countdown timer.
import time
n = int(input("Enter time in seconds: ")) # Input: 5
for i in range(n, 0, -1):
print(i)
time.sleep(1)
print("Time's up!")
Output:
5
4
3
2
1
Time's up!

93. Print All Prime Numbers Up to N


Question: Write a program to print all prime numbers up to N.
n = int(input("Enter N: ")) # Input: 10
for num in range(2, n + 1):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num, end=' ')
Output: 2 3 5 7
94. Check if a Number is a Perfect Square
Question: Write a program to check if a number is a perfect square.
import math
num = int(input("Enter a number: ")) # Input: 16
sqrt = int(math.sqrt(num))
if sqrt * sqrt == num:
print(f"{num} is a perfect square.")
else:
print(f"{num} is not a perfect square.")
Output: 16 is a perfect square.

95. Reverse the Order of Words in a Sentence


Question: Write a program to reverse the order of words in a sentence.
sentence = input("Enter a sentence: ") # Input: Hello World
reversed_sentence = ' '.join(sentence.split()[::-1])
print(f"Reversed sentence: {reversed_sentence}")
Output: Reversed sentence: World Hello

96. Count the Number of Uppercase Letters in a String


Question: Write a program to count the number of uppercase letters in a string.
string = input("Enter a string: ") # Input: Hello World
uppercase_count = sum(1 for char in string if char.isupper())
print(f"Number of uppercase letters: {uppercase_count}")
Output: Number of uppercase letters: 2
98. Find the Smallest Divisor of a Number
Question: Write a program to find the smallest divisor of a number greater than
1.
num = int(input("Enter a number greater than 1: ")) # Input: 15
for i in range(2, num + 1):
if num % i == 0:
print(f"Smallest divisor of {num} greater than 1 is: {i}")
break
Output: Smallest divisor of 15 greater than 1 is: 3

99. Check if Two Strings are Anagrams


Question: Write a program to check if two strings are anagrams of each other.
str1 = input("Enter first string: ") # Input: listen
str2 = input("Enter second string: ") # Input: silent
if sorted(str1) == sorted(str2):
print(f"{str1} and {str2} are anagrams.")
else:
print(f"{str1} and {str2} are not anagrams.")
Output: listen and silent are anagrams.

100. Find All the Unique Elements in a List


Question: Write a program to find all unique elements in a list.
arr = input("Enter numbers separated by space: ").split() # Input: 1 2 2 3 4 4
unique_elements = list(set(arr))
print(f"Unique elements: {unique_elements}")
Output: Unique elements: ['1', '2', '3', '4']

You might also like