Python Top Exercises
Python program to swap two variables
Description: Write a Python program to swap the values of two variables.
Rules and hints:
- Do it first with a third (temporary) variable.
- Then do it the Python way, in one line.
Python program to swap two variables
a = 10
b = 20
print("Before swap: a =", a, "b =", b)
a, b = b, a
print("After swap: a =", a, "b =", b)
Output:
Before swap: a = 10 b = 20
After swap: a = 20 b = 10
How it works
- The line
a, b = b, abuilds a tuple(b, a)and unpacks it intoaandb. - In many other languages you need a third variable:
temp = a,a = b,b = temp. That also works in Python. - Swapping works with any type, not only numbers.
Python program to check even or odd number
Description: Write a Python program to check whether a number is even or odd.
Rules and hints:
- A number is even if it is divisible by 2.
- Use the modulus operator
%, which gives the remainder.
Python program to check even or odd
for number in (4, 7):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
Output:
4 is even
7 is odd
How it works
4 % 2is 0, so 4 is even.7 % 2is 1, so theelsepart runs and 7 is odd.- Negative numbers also work, because
-3 % 2is 1 in Python.
Learn the basics in Python Conditional Statements.
Python program to check leap year
Description: Write a Python program to check whether a year is a leap year.
Rules and hints:
- A year is a leap year if it is divisible by 4 but not by 100.
- A year divisible by 400 is also a leap year.
Python program to check a leap year
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
for year in (2024, 1900, 2000, 2023):
if is_leap(year):
print(year, "is a leap year")
else:
print(year, "is not a leap year")
Output:
2024 is a leap year
1900 is not a leap year
2000 is a leap year
2023 is not a leap year
How it works
- 2024 is divisible by 4 and not by 100, so it is a leap year.
- 1900 is divisible by 100 but not by 400, so it is not a leap year.
- 2000 is divisible by 400, so it is a leap year.
- 2023 is not divisible by 4.
Python program to find factorial of a number
Description: Write a Python program to find the factorial of a number using a loop.
Rules and hints:
- Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
- Start with 1 and multiply by each number.
Python program for factorial using a loop
num = 5
factorial = 1
for i in range(1, num + 1):
factorial = factorial * i
print("Factorial of", num, "is", factorial)
Output:
Factorial of 5 is 120
How it works
factorialstarts with 1.- The loop multiplies it with 1, 2, 3, 4 and 5 one by one: 1, 2, 6, 24, 120.
- For 0, the loop does not run, and the answer stays 1, which is correct.
You can also solve it with a function that calls itself. See Python Functions (recursion).
Python program to print Fibonacci series
Description: Write a Python program to print the first 10 numbers of the Fibonacci series.
Rules and hints:
- Each number is the sum of the two numbers before it.
- The series starts with 0 and 1.
Python program for Fibonacci series
a, b = 0, 1
for _ in range(10):
print(a, end=" ")
a, b = b, a + b
Output:
0 1 1 2 3 5 8 13 21 34
How it works
aandbhold two neighbour numbers of the series.print(a, end=" ")prints on the same line with a space.a, b = b, a + bmoves to the next pair at once.- The loop variable
_means we do not use its value.
Python program to check prime number
Description: Write a Python program to check whether a number is prime.
Rules and hints:
- A prime number is greater than 1 and has no divisor other than 1 and itself.
- You only need to test divisors up to the square root of the number.
Python program to check a prime number
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
for n in (2, 15, 17, 1):
if is_prime(n):
print(n, "is prime")
else:
print(n, "is not prime")
Output:
2 is prime
15 is not prime
17 is prime
1 is not prime
How it works
- Numbers below 2 are not prime.
- For 15 the loop tests 2 and 3. Since
15 % 3 == 0, it returnsFalse. - For 17 the loop tests 2, 3 and 4. None divides it, so it is prime.
- As soon as one divisor is found,
return Falseends the function early.
Python program to check palindrome string
Description: Write a Python program to check whether a string is a palindrome.
Rules and hints:
- A palindrome reads the same from both sides, like
madam. - Ignore upper and lower case.
Python program to check a palindrome
def is_palindrome(text):
text = text.lower()
return text == text[::-1]
for word in ("madam", "Level", "python"):
if is_palindrome(word):
print(word, "is a palindrome")
else:
print(word, "is not a palindrome")
Output:
madam is a palindrome
Level is a palindrome
python is not a palindrome
How it works
lower()changes the text to lowercase, so “Level” becomes “level”.text[::-1]is the reversed string.- If the text equals its reverse, it is a palindrome.
Read about slicing in Python Strings.
Python program to reverse a string
Description: Write a Python program to reverse a string in three different ways.
Rules and hints:
- Strings are immutable, so you create a new string.
Python program to reverse a string
text = "Python"
# 1. slicing
print(text[::-1])
# 2. reversed() and join()
print("".join(reversed(text)))
# 3. loop
result = ""
for ch in text:
result = ch + result
print(result)
Output:
nohtyP
nohtyP
nohtyP
How it works
- Slicing with step
-1goes through the string from the end. reversed()gives the characters in reverse order, andjoin()makes a string again.- In the loop, every new character is added to the front of
result.
Related: join() function.
Python program to remove duplicates from a list
Description: Write a Python program to remove the duplicate items from a list.
Rules and hints:
- A set keeps only unique values, but it does not keep the order.
dict.fromkeys()keeps the order of the first appearance.
Python program to remove duplicates from a list
items = [1, 2, 2, 3, 4, 4, 5]
unique_sorted = sorted(set(items))
unique_ordered = list(dict.fromkeys(items))
print(unique_sorted)
print(unique_ordered)
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
How it works
set(items)removes the duplicates, andsorted()makes a sorted list of it.- A dictionary cannot have duplicate keys, and in Python 3.7+ it keeps the insertion order. So
dict.fromkeys(items)followed bylist()keeps the first order.
Related: Python Sets and Python Dictionary.
Python program to find the sum of natural numbers using recursion
Description: Write a Python program to find the sum of the first n natural numbers using recursion.
Rules and hints:
- A recursive function calls itself.
- Every recursive function needs a stopping (base) case.
Python program for the sum of natural numbers using recursion
def sum_to(n):
if n == 0:
return 0 # base case
return n + sum_to(n - 1)
print(sum_to(5))
print(sum_to(10))
Output:
15
55
How it works
sum_to(5)returns 5 +sum_to(4), and so on, down tosum_to(0)which returns 0.- The results come back as 0, 1, 3, 6, 10 and 15.
- Without the base case the function would never stop and Python would raise a
RecursionError.
See the Recursion section of Python Functions.