Exciting Python Coding Challenges for Beginners

Shantun Parmar
5 min readSep 2, 2024

--

Python Coding Challenges for Beginners

Thanks in great part to its simplicity, diversity, and ease of use, Python’s popularity as a programming language has soared recently. Nonetheless, understanding Python’s technical complexity can be challenging, so beginners could find it tough to get a strong hold on the language. Regularly completing coding challenges might be a great approach to improve one’s Python knowledge and abilities in order to get beyond this: These difficulties offer a chance to gain practical experience, develop your knowledge of Python programming concepts, and learn how to use them in actual settings.

This article addresses few python code challenges meant especially for beginners to help them improve their coding abilities and reach their programming goals. These carefully chosen activities provide a fantastic forum for learning and development as they test and improve coding skills. This article highlights the need of coding difficulties in enhancing Python competency and offers some easy tasks to assist you to start with Python programming.

Printing Items from a List

Python’s basic data structure is lists, hence every future programmer must be adept in their manipulation. In this assignment, you will list fruits using a for loop and print each item on a fresh line using a Clarify your Python list and control structure knowledge.

# Define a list of items
items = ['apple', 'banana', 'cherry', 'date']

# Loop through the list and print each item
for item in items:
print(item)

Create binary from a decimal number

Create a Python function accepting a decimal value that generates the corresponding binary number. Simply said, the decimal number will always be less than 1,024, So the binary number produced will always be less than 10 digit long.

def decimal_to_binary(decimal_value):
# Ensure the input is an integer and within the valid range
if not isinstance(decimal_value, int) or not (0 <= decimal_value < 1024):
raise ValueError("Input must be an integer between 0 and 1023 inclusive.")

# Convert the decimal number to binary and remove the '0b' prefix
binary_value = bin(decimal_value)[2:]

# Return the binary number, padded to ensure it's less than 10 digits
return binary_value.zfill(10)

# Example usage
decimal_number = 42
binary_number = decimal_to_binary(decimal_number)
print(f"Decimal: {decimal_number} -> Binary: {binary_number}")

Count the vowels in a string

Write a Python function accepting one word that counts the vowels in that word. This will count just a, e, i, o, and u as vowels.

def count_vowels(word):
# Define a set of vowels
vowels = {'a', 'e', 'i', 'o', 'u'}

# Initialize a counter for vowels
vowel_count = 0

# Iterate through each character in the word
for char in word.lower(): # Convert the word to lowercase for case-insensitive comparison
if char in vowels:
vowel_count += 1

return vowel_count

# Example usage
word = "Example"
print(f"The number of vowels in '{word}' is {count_vowels(word)}")

Identical items from two sets

In Python, sets are a really effective data structure, knowing how to interact with them may be quite helpful. This assignment will have you create a Python code to identify exactly matching objects in two collections. Enter the realm of set operations and increase your Python toolset for solving problems.

def find_exact_matches(collection1, collection2):
# Convert collections to sets to remove duplicates and enable set operations
set1 = set(collection1)
set2 = set(collection2)

# Find intersection of the two sets
matching_items = set1 & set2

return matching_items

# Example usage
collection1 = ['apple', 'banana', 'cherry', 'date', 'banana']
collection2 = ['banana', 'cherry', 'fig', 'grape']

matching_items = find_exact_matches(collection1, collection2)
print(f"Matching items: {matching_items}")

Create a Calculator Function

Provide a Python function with three arguments. An integer should be the first argument; a mathematical operator — +, -, /, or, and the third parameter should also be an integer.

The function need to be able to compute the answers and back off.

def compute_operation(num1, operator, num2):
try:
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
return "Error: Division by zero is not allowed."
result = num1 / num2
else:
return "Error: Invalid operator. Please use '+', '-', '*', or '/'."

return result

except Exception as e:
return f"An error occurred: {e}"

# Example usage
print(compute_operation(10, '+', 5)) # Output: 15
print(compute_operation(10, '-', 3)) # Output: 7
print(compute_operation(10, '*', 4)) # Output: 40
print(compute_operation(10, '/', 2)) # Output: 5.0
print(compute_operation(10, '/', 0)) # Output: Error: Division by zero is not allowed.
print(compute_operation(10, '^', 2)) # Output: Error: Invalid operator. Please use '+', '-', '*', or '/'.

Just the numbers

Write a Python function called “get_integers” to take strings and a list of mixed non-negative integers. The function ought to filter and produce just the integers in the same sequence as they show in the original list.

def get_integers(mixed_list):
# Use a list comprehension to filter out only integers
integers = [item for item in mixed_list if isinstance(item, int)]

return integers

# Example usage
mixed_list = ['apple', 10, 'banana', 23, 'cherry', 42]
integers = get_integers(mixed_list)
print(integers) # Output: [10, 23, 42]

Arguments Printing on Different Lines

You may have to provide several values in a neat and orderly fashion. In this assignment, you will design a Python function utilizing keyword arguments that outputs two parameters on distinct lines. Improve your ability to write functionally and pick to use keyword arguments’ power.

def print_values(param1, param2):
print(f"First parameter: {param1}")
print(f"Second parameter: {param2}")

# Example usage with keyword arguments
print_values(param1="Hello", param2="World")

First and Last Five Rows

Quickly previewing the first and final few rows of a Pandas DataFrame can enable one easily deal with big datasets. You will create a Python function in this challenge printing the first five rows and the final five rows of a given DataFrame. This simple tool will help you to simplify your data investigation and analysis.

import pandas as pd

def preview_dataframe(df):
if not isinstance(df, pd.DataFrame):
raise ValueError("The input must be a Pandas DataFrame.")

# Print the first five rows
print("First five rows:")
print(df.head())
print() # Print a newline for better readability

# Print the last five rows
print("Last five rows:")

Python inverts dictionaries

Although dictionaries are a basic Python data structure, what if you must exchange the keys and values? This challenge will have you create a Python function to invert a dictionary, which has applications in many contexts, including key search based on value. Release dictionaries’ adaptability and improve your Python ability to solve problems.

def invert_dictionary(original_dict):
if not all(isinstance(v, (int, float, str)) for v in original_dict.values()):
raise ValueError("All dictionary values must be hashable types (e.g., int, float, str).")

# Invert the dictionary by swapping keys and values
inverted_dict = {value: key for key, value in original_dict.items()}

return inverted_dict

# Example usage
original_dict = {
'a': 1,
'b': 2,
'c': 3
}

inverted_dict = invert_dictionary(original_dict)
print("Original Dictionary:", original_dict)
print("Inverted Dictionary:", inverted_dict)

Conclusion

Learning Python programming calls for regular practice; solving coding problems is an excellent approach to advance one’s abilities. Beginning users who are just starting their path in Python programming will find the seven Python code challenges covered in this blog suitable. These difficulties provide people a strong basis from which to grow and enable them to grasp Python’s syntax and features more fully. Through constant practice of these tasks, novices can progressively raise their Python programming competency. Thus, start working on these issues right now to advance to be a competent Python coder.

--

--

Shantun Parmar

Software Engineer | Full Stack Developer | Python | JavaScript | Problem Solver https://bit.ly/3V9HoR9