Python Practice questions
Top 50 Python Practice Questions with Solutions
Sharpen your Python skills with real-world coding challenges
1. Reverse a String
text = "hello"
reversed_text = text[::-1]
print(reversed_text) # Output: olleh
2. Check if a Number is Prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(13)) # Output: True
3. Find the Factorial of a Number
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
print(factorial(5)) # Output: 120
4. Check for a Palindrome
def is_palindrome(text):
return text == text[::-1]
print(is_palindrome("madam")) # Output: True
5. Find the Largest Element in a List
numbers = [3, 5, 1, 8, 2]
print(max(numbers)) # Output: 8
6. Count Vowels in a String
def count_vowels(s):
return sum(1 for char in s.lower() if char in "aeiou")
print(count_vowels("Python")) # Output: 1
7. Sum of Elements in a List
nums = [10, 20, 30]
print(sum(nums)) # Output: 60
8. Fibonacci Series up to n Terms
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(5) # Output: 0 1 1 2 3
9. Remove Duplicates from a List
my_list = [1, 2, 2, 3, 4, 4]
unique = list(set(my_list))
print(unique) # Output: [1, 2, 3, 4]
10. Check if a Year is Leap Year
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(is_leap(2024)) # Output: True
11. Find the Second Largest Number in a List
def second_largest(numbers):
unique = list(set(numbers))
unique.sort()
return unique[-2]
print(second_largest([5, 1, 8, 2, 8])) # Output: 5
12. Check if Two Strings are Anagrams
def are_anagrams(s1, s2):
return sorted(s1) == sorted(s2)
print(are_anagrams("listen", "silent")) # Output: True
13. Find GCD of Two Numbers
import math
print(math.gcd(36, 60)) # Output: 12
14. Count Frequency of Each Character in a String
from collections import Counter
s = "programming"
print(Counter(s)) # Output: {'r': 2, 'o': 1, 'g': 2, ...}
15. Find All Even Numbers in a List
numbers = [1, 4, 7, 10, 13]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # Output: [4, 10]
16. Remove Punctuation from a String
import string
s = "Hello, World!"
cleaned = ''.join(c for c in s if c not in string.punctuation)
print(cleaned) # Output: Hello World
17. Merge Two Dictionaries
a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
merged = {**a, **b}
print(merged) # Output: {'x': 1, 'y': 3, 'z': 4}
18. Find the Length of the Longest Word
words = ["apple", "banana", "grapefruit"]
longest = max(words, key=len)
print(longest) # Output: grapefruit
19. Get the Sum of Digits in a Number
n = 1234
total = sum(int(digit) for digit in str(n))
print(total) # Output: 10
20. Check if a List is Sorted
def is_sorted(lst):
return lst == sorted(lst)
print(is_sorted([1, 2, 3])) # Output: True
print(is_sorted([3, 2, 1])) # Output: False
21. Count Words in a Sentence
sentence = "Python is fun and powerful"
word_count = len(sentence.split())
print(word_count) # Output: 5
22. Check if a Number is Armstrong
def is_armstrong(n):
return n == sum(int(d)**3 for d in str(n))
print(is_armstrong(153)) # Output: True
23. Find All the Divisors of a Number
def divisors(n):
return [i for i in range(1, n+1) if n % i == 0]
print(divisors(12)) # Output: [1, 2, 3, 4, 6, 12]
24. Count Occurrences of a Word in a Sentence
text = "Python is easy. Python is powerful."
count = text.lower().count("python")
print(count) # Output: 2
25. Remove Duplicates Without Using Set
lst = [1, 2, 2, 3, 3, 4]
unique = []
for i in lst:
if i not in unique:
unique.append(i)
print(unique) # Output: [1, 2, 3, 4]
26. Flatten a 2D List
matrix = [[1, 2], [3, 4], [5]]
flattened = [item for row in matrix for item in row]
print(flattened) # Output: [1, 2, 3, 4, 5]
27. Swap Two Variables Without a Temp
a, b = 10, 20
a, b = b, a
print(a, b) # Output: 20 10
28. Convert Celsius to Fahrenheit
def c_to_f(c):
return (c * 9/5) + 32
print(c_to_f(0)) # Output: 32.0
29. Get All Unique Elements from List
lst = [1, 2, 2, 3, 4, 4]
unique = list(set(lst))
print(unique) # Output: [1, 2, 3, 4]
30. Find the Most Frequent Element
from collections import Counter
lst = [1, 2, 2, 3, 3, 3, 4]
most_common = Counter(lst).most_common(1)[0][0]
print(most_common) # Output: 3
31. Calculate Factorial Using Recursion
def factorial(n):
return 1 if n == 0 else n * factorial(n - 1)
print(factorial(5)) # Output: 120
32. Print Fibonacci Series
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(7) # Output: 0 1 1 2 3 5 8
33. Reverse a List
lst = [1, 2, 3, 4]
print(lst[::-1]) # Output: [4, 3, 2, 1]
34. Check if a Number is Prime
def is_prime(n):
if n <= 1: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True
print(is_prime(7)) # Output: True
35. Find Largest Word in a Sentence
sentence = "Python is an awesome language"
words = sentence.split()
largest = max(words, key=len)
print(largest) # Output: language
36. Remove Vowels from a String
s = "Hello World"
result = ''.join(c for c in s if c.lower() not in 'aeiou')
print(result) # Output: Hll Wrld
37. Sort a List of Tuples by Second Element
pairs = [(1, 3), (2, 2), (4, 1)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # Output: [(4, 1), (2, 2), (1, 3)]
38. Capitalize First Letter of Each Word
text = "hello world"
print(text.title()) # Output: Hello World
39. Convert a List to a Dictionary
keys = ['a', 'b', 'c']
values = [1, 2, 3]
result = dict(zip(keys, values))
print(result) # Output: {'a': 1, 'b': 2, 'c': 3}
40. Check if a Substring Exists
s = "python programming"
print("gram" in s) # Output: True
41. Find ASCII Value of a Character
print(ord('A')) # Output: 65
42. Convert String to List of Characters
s = "hello"
print(list(s)) # Output: ['h', 'e', 'l', 'l', 'o']
43. Get Common Elements in Two Lists
a = [1, 2, 3]
b = [2, 3, 4]
common = list(set(a) & set(b))
print(common) # Output: [2, 3]
44. Count Uppercase Letters
s = "Hello World"
count = sum(1 for c in s if c.isupper())
print(count) # Output: 2
45. Replace Spaces with Hyphens
s = "Python is fun"
print(s.replace(" ", "-")) # Output: Python-is-fun
46. Get Last Digit of a Number
n = 12345
print(n % 10) # Output: 5
47. Get All Indexes of a Value in List
lst = [1, 2, 3, 2, 4]
indexes = [i for i, val in enumerate(lst) if val == 2]
print(indexes) # Output: [1, 3]
48. Check Palindrome Using Loop
def is_palindrome(s):
for i in range(len(s)//2):
if s[i] != s[-(i+1)]:
return False
return True
print(is_palindrome("madam")) # Output: True
49. Sum of List Elements Using Loop
lst = [1, 2, 3, 4]
total = 0
for num in lst:
total += num
print(total) # Output: 10
50. Check if Year is Leap Year
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
print(is_leap(2024)) # Output: True
Comments
Post a Comment