15 Simple Python Programs for Practice with Solutions

15-simple-python-programs-for-practice-for-beginners

To get a good grip on a programming language, you should practice what you’ve learned. Once you have finished learning the basic syntax of Python programming language, You must do some practice programs.

In this article, I will share a list of Python programming exercises with their answer codes. First try to solve each problem on your own, if you have any questions then you can refer to the code.

Course for You: Learn Python in 100 days of coding

1. Check if a given number is prime or not

A prime number is a whole number that can only be divided by 1 and itself without leaving a remainder. For example, 2, 3, 5, 7, 11, and 13 are prime numbers. Below is the Python program to check if a given number is prime or not.

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

# This is the input number to check prime or not
num = 17

if is_prime(num):
    print(num, "is a prime number.")
else:
    print(num, "is not a prime number.")

Output:

17 is a prime number.

2. Even or Odd

Write a Python program to determine if a number is even or odd. Even numbers are divisible by 2 without any remainder, while odd numbers are not divisible by 2 and leave a remainder of 1 when divided by 2. Every integer is either even or odd, there are no other possibilities.

# This is the number to check even or not
num = 7

if num % 2 == 0:
    print(num, "is an even number.")
else:
    print(num, "is an odd number.")

Output:

7 is an odd number.

3. Generate the Fibonacci series up to a certain number

The Fibonacci series is a sequence of numbers where each number is the sum of the two numbers before it. It starts with 0 and 1, and goes like this: 0, 1, 1, 2, 3, 5, 8, and so on. Each number is found by adding the two previous numbers. It has many uses in mathematics.

# fibonacci series python programs for practice
def fibonacci(n):
    fib_series = [0, 1]
    while fib_series[-1] + fib_series[-2] <= n:
        next_num = fib_series[-1] + fib_series[-2]
        fib_series.append(next_num)
    return fib_series


limit = input('Enter the max number to generate Fibonacci Series: ')
print("Fibonacci Series up to", limit, ":", fibonacci(int(limit)))

Output:

Enter the max number to generate Fibonacci Series: 50
Fibonacci Series up to 50 : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Enter the max number to generate Fibonacci Series: 15
Fibonacci Series up to 15 : [0, 1, 1, 2, 3, 5, 8, 13]

You have noticed that, I used input() statement in the above Python code. The value passed through an input() statement is always a string. So you need to convert this string input to an integer by int() statement.

4. Calculate the factorial of a number

Write a Python programs to calculate the factorial of a given number for practice. The factorial of a number is a way to find the product of all positive whole numbers from 1 to that number. For example, the factorial of 5, written as 5!, is calculated like this: 5! = 5 x 4 x 3 x 2 x 1 = 120.

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

# Calculate factorial for this number
num = 5
print("Factorial of", num, "is", factorial(num))

Output:

Factorial of 5 is 120

5. String Reversal

Write a program to reverse a given input string. I faced this Python coding question in one of my interviews a few years back.

def reverse_string(s):
    return s[::-1]

input_str = "Python is amazing!"
print("Reversed String:", reverse_string(input_str))

Output:

Reversed String: !gnizama si nohtyP

6. Leap Year Checker

Determine if a given year is a leap year. If the year is divisible by 4 and not divisible by 100, it’s a leap year. However, if it’s divisible by 400, it’s still a leap year.

Also Read:  14 Python Exercises for Intermediate with Solutions

For example, the year 2024 is divisible by 4 but not by 100, so it’s a leap year. The year 2100 is divisible by 4 and 100, but not by 400, so it’s not a leap year. But the year 2000 is divisible by 400, so it is a leap year. This rule helps keep our calendar accurate.

def is_leap_year(year):
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        return True
    return False

year = input('Enter year to check Leap Year or Not: ')

if is_leap_year(int(year)):
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")

Output:

Enter year to check Leap Year or Not: 2020
2020 is a leap year.
Enter year to check Leap Year or Not: 2100
2100 is not a leap year.

7. Unique Elements

Write a Python program to find unique elements in a list.

def unique_elements(arr):
    unique_list = []
    for item in arr:
        if item not in unique_list:
            unique_list.append(item)
    return unique_list

# Input list
my_list = [1, 2, 2, 3, 4, 4, 5]
print("Unique Elements:", unique_elements(my_list))
Unique Elements: [1, 2, 3, 4, 5]

Now above code is for those who want to learn things from basics. You can achieve same result using set() function of Python. Below is the code to do that.

# Input list
my_list = [1, 2, 2, 3, 4, 4, 5]

# Unique elements
list(set(my_list))
[1, 2, 3, 4, 5]

8. Bubble Sort

Implement the Bubble Sort algorithm to sort a list of numbers in Python. This type of exercises are for beginners who want to learn core data structure using Python.

Imagine you have a row of students, and you want to arrange them from shortest to tallest. Bubble sort is like having them compare their heights with the person next to them and swapping places if needed, until everyone is in the right order.

It’s called “bubble” sort because the smaller items (like bubbles) gradually move up to the top, just like bubbles rise in water. It’s not the most efficient sorting method for large lists, but it’s easy to understand and can be handy for small sets of data.

# Bubble short practice programs in Python
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# Input list
my_list = [64, 34, 25, 12, 22, 11, 90]
print("Sorted List:", bubble_sort(my_list))
Sorted List: [11, 12, 22, 25, 34, 64, 90]

Implement the Binary Search algorithm to find an element in a sorted list in Python.

Also Read:  15 Python while Loop Exercises with Solutions for Beginners

Binary search is like finding a word in a dictionary. Instead of flipping through each page one by one, you open the dictionary in the middle and decide whether the word you’re looking for is in the first half or the second half. Then, you repeat the process with that half, and so on. It’s a quick way to find things in a sorted list because it reduces the search space by half each time.

# Python exercise program to find index value of a sorted binary search
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# input list
sorted_list = [2, 4, 6, 8, 10, 12, 14, 16]
# Input target value
target = 8
index = binary_search(sorted_list, target)
if index != -1:
    print(target, "found at index", index)
else:
    print(target, "not found in the list.")
8 found at index 3

10. File Handling

Python practice programs to read and write data to a text file. This is one of the most frequent methods you use while working in the data science field, especially in Natural Language Processing.

# Writing to a file
with open("sample.txt", "w") as file:
    file.write("Hello, this is a sample text file.")

# Reading from a file
with open("sample.txt", "r") as file:
    content = file.read()
    print("File Content:", content)
File Content: Hello, this is a sample text file.

Above code will create a .txt file inside your working directory named “sample.txt“. Inside this sample.txt you can find text “Hello, this is a sample text file.”.

11. URL Parsing

Parse a URL and extract its components using Python. Web scraping is so important to learn if you are planning to work as a data engineer. Below code is just a simple beginner exercise to scrape a website using Python and display basic information.

from urllib.parse import urlparse

url = "https://en.wikipedia.org/wiki/Python_(programming_language)"
parsed_url = urlparse(url)

print("Scheme:", parsed_url.scheme)
print("Netloc:", parsed_url.netloc)
print("Path:", parsed_url.path)
Scheme: https
Netloc: en.wikipedia.org
Path: /wiki/Python_(programming_language)

12. Generate Random Numbers

Write a Python program to generate a random number within a specified range.

# Generate random number in Python
import random

lower_limit = 1
upper_limit = 100
random_num = random.randint(lower_limit, upper_limit)
print("Random Number between", lower_limit, "and", upper_limit, ":", random_num)
Random Number between 1 and 100 : 21

Since the above code generates a random number, the resulting number may be different for you while running this Python code.

13. Count Vowels and Consonants

Write a practice Python programs to count the number of vowels and consonants in a string.

# Python practice programs: count the number of vowels and consonants in a string
def count_vowels_and_consonants(text):
    vowels = "aeiouAEIOU"
    vowel_count = 0
    consonant_count = 0
    
    vowel_char = []
    consonant_char = []
    for char in text:
        if char.isalpha():
            if char in vowels:
                vowel_count += 1
                vowel_char.append(char)
            else:
                consonant_count += 1
                consonant_char.append(char)
    return vowel_count, vowel_char, consonant_count, consonant_char

# Input text
text = "Python programming is fun!"
vowels, vowel_char, consonants, consonant_char = count_vowels_and_consonants(text)
print("Vowels:", vowels)
print("Vowels:", vowel_char)
print("Consonants:", consonants)
print("Consonants:", consonant_char)
Vowels: 6
Vowels: ['o', 'o', 'a', 'i', 'i', 'u']
Consonants: 16
Consonants: ['P', 'y', 't', 'h', 'n', 'p', 'r', 'g', 'r', 'm', 'm', 'n', 'g', 's', 'f', 'n']

14. Reverse a List

Write a practice Python program pdf to reverse a list.

def reverse_list(lst):
    return lst[::-1]

# Input list to reverse
my_list = [1, 2, 3, 4, 5]
print("Reversed List:", reverse_list(my_list))
Reversed List: [5, 4, 3, 2, 1]

15. Calculate the Area of a Triangle

Write a practice Python program to calculate the area of a triangle given its base and height.

# python programs for practice: Calculate area of a traiangle
def triangle_area(base, height):
    return 0.5 * base * height

base_length = 6
height = 8
print("Area of the triangle:", triangle_area(base_length, height))
Area of the triangle: 24.0

Conclusion

In this article, I have listed down some Python programs for practice, you can use this as a pdf and practice whenever you want. These exercise codes will help you to gain confidence in Python programming language while appearing in an interview.

Also Read:  18 Python print Function Exercises with Solutions for Beginners

Once you feel confident, You should learn how to develop something by utilizing your Python skill. For example, you can learn to code how to Build a desktop application using Python like a calculator app, Analog Digital Clock, Stopwatch, Desktop notifier, etc.

Or develop web applications using Python like: Building sentiment Analysis Flask Web App, Deploy Object detection model using Flask, etc.

This is it for this article. If you want to learn Python quickly then this Udemy course is for you: Learn Python in 100 days of coding. If you are a person who loves learning from books then this article is for you: 5 Best Book for Learning Python. See you in the comment section below.

Similar Read:

Leave a comment