Are you ready to embark on your journey to become a Python pro? Here is the Beginner Python Exercises With Solution Code included. As python known for its simplicity and versatility, is an excellent choice for beginners. To kickstart your Python adventure, we have put together a collection of 15 beginner-friendly exercises that cover the fundamental concepts of Python programming.
So, grab your coding gear and let’s dive into these Python basics!
Table of Contents
- Calculate the multiplication and sum of two numbers
- Print the sum of the current and previous number
- Print characters from a string at even index positions
- Remove first n characters from a string
- Check if the first and last number of a list is the same
- Display numbers divisible by 5 from a list
- Count occurrences of a substring in a string
- Print a pattern of numbers
- Check Palindrome Number
- Create a new list from two lists based on conditions
- Extract each digit from an integer in reverse order
- Calculate income tax for a given income
- Print multiplication table from 1 to 10
- Print a downward Half-Pyramid Pattern of Star (asterisk)
- Calculate exponentiation in Python
Let’s get started with our Beginner Python Exercise journey!
1. Calculate the multiplication and sum of two numbers
In this exercise, you’ll write Python code to calculate the product of two numbers if it’s less than or equal to 1000; otherwise, you’ll find their sum. The calculate_product_or_sum
function takes two numbers as input, calculates their product, and checks if the product is less than or equal to 1000. If it is, it returns the product; otherwise, it returns the sum of the two numbers. Following in the code example:
Example:
def calculate_product_or_sum(number1, number2):
product = number1 * number2
if product <= 1000:
return f"The result is {product}"
else:
return f"The result is {number1 + number2}"
// Example usage:
result1 = calculate_product_or_sum(20, 30)
print(result1) // Output: The result is 600
result2 = calculate_product_or_sum(40, 30)
print(result2) // Output: The result is 70
2. Print the sum of the current and previous number
Here, you’ll create a program that iterates through the first 10 numbers and prints the sum of the current and previous numbers. The print_sum_of_numbers
function prints the sum of the current and previous numbers in a loop. It starts with a previous number of 0 and iterates through numbers from 0 to 9.
Example:
def print_sum_of_numbers():
previous_number = 0
for current_number in range(10):
sum_of_numbers = current_number + previous_number
print(f"Current Number {current_number} Previous Number {previous_number} Sum: {sum_of_numbers}")
previous_number = current_number
// Example usage:
print_sum_of_numbers()
3. Print characters from a string at even index positions
This exercise requires you to accept a string from the user and display characters present at even index positions. The print_even_index_characters
function takes an input string and prints characters at even index positions (0, 2, 4, etc.). It uses a for loop to iterate through the string.
Example:
def print_even_index_characters(input_string):
print(f"Original String is {input_string}")
print("Printing only even index chars")
for index in range(0, len(input_string), 2):
print(input_string[index])
// Example usage:
input_str = "pynative"
print_even_index_characters(input_str)
4. Remove first n characters from a string
You’ll write a program to remove the first n characters from a given string and return the modified string. The remove_chars
function removes the first n
characters from an input string if n
is less than the length of the string. If n
is greater than or equal to the string length, it returns an error message.
Example:
def remove_chars(input_string, n):
if n < len(input_string):
return input_string[n:]
else:
return "n must be less than the length of the string."
// Example usage:
result1 = remove_chars("pynative", 4)
print(result1) // Output: "tive"
result2 = remove_chars("pynative", 2)
print(result2) // Output: "native"
Certainly! input_string[n:]
in Python is a way to create a new string that contains all characters in the input_string
starting from the n
-th position (inclusive) to the end of the string.
Here’s a breakdown:
input_string
: This is the original string from which you want to remove characters.[n:]
: The square brackets[]
are used to slice a string. In this case, it means you want to start from then
-th character (indexn
) and include all characters afterward.
For example, if you have the string "pynative"
and you use input_string[2:]
, it would take all characters starting from the 3rd character (index 2, which is “n”) to the end of the string. So, the result would be "native"
.
Similarly, if you have input_string[4:]
, it would start from the 5th character (index 4, which is “a”) and include all characters afterward, resulting in "tive"
.
It’s a way to extract a portion of a string in Python, starting from a specific index and continuing to the end of the string.
5. Check if the first and last number of a list is the same
Write a function that returns True if the first and last numbers of a given list are the same, and False otherwise. The function is_first_and_last_same
checks if the list has at least two elements and if the first and last elements are the same. If they are, it returns True
; otherwise, it returns False
.
Example:
def is_first_and_last_same(numbers):
if len(numbers) >= 2 and numbers[0] == numbers[-1]:
return True
else:
return False
// Example usage:
numbers_x = [10, 20, 30, 40, 10]
result_x = is_first_and_last_same(numbers_x)
print(result_x) // Output: True
numbers_y = [75, 65, 35, 75, 30]
result_y = is_first_and_last_same(numbers_y)
print(result_y) // Output: False
6. Display numbers divisible by 5 from a list
Iterate through a given list of numbers and print only those numbers that are divisible by 5. The function divisible_by_5
iterates through the given list of numbers and checks if each number is divisible by 5. If it is, it prints the number.
Expected Output:
def divisible_by_5(numbers):
print("Divisible by 5:")
for num in numbers:
if num % 5 == 0:
print(num)
// Example usage:
given_list = [10, 20, 33, 46, 55]
divisible_by_5(given_list)
7. Count occurrences of a substring in a string
Create a program to find how many times the substring “Emma” appears in a given string. The function count_substring_occurrences
uses the count
method of strings to count the occurrences of a substring in a given string.
Example:
def count_substring_occurrences(main_string, substring):
count = main_string.count(substring)
return f"{substring} appeared {count} times"
// Example usage:
str_x = "Emma is a good developer. Emma is a writer"
result_x = count_substring_occurrences(str_x, "Emma")
print(result_x) // Output: "Emma appeared 2 times"
8. Print a pattern of numbers using python
This exercise involves printing a specific pattern of numbers. Get ready to flex your loop skills! The function print_number_pattern
prints a pattern of numbers as described in the exercise. It uses nested loops to achieve this pattern.
Example:
def print_number_pattern(rows):
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(i, end=" ")
print("")
// Example usage:
print_number_pattern(5)
The line of code for i in range(1, rows + 1):
is a Python for loop that iterates through a range of numbers. Let me explain it in plain English:
for i
: This part of the statement signifies that you’re creating a loop wherei
will take on the values in the specified range one by one.in range(1, rows + 1)
: Here’s what this part means:range(1, rows + 1)
: This is a Python functionrange()
that generates a sequence of numbers starting from1
(inclusive) up to, but not including,rows + 1
.rows + 1
is used because you want the loop to include the value ofrows
itself.
So, when you write for i in range(1, rows + 1):
, it means that i
will take on values from 1
to rows
(inclusive), and the loop will execute once for each value of i
. This is commonly used in Python to iterate over a sequence of numbers or perform a task a specific number of times (controlled by the rows
variable in this case).
9. How to Check Palindrome Number in Python
Write a program to check if a given number is a palindrome. A palindrome number is the same when read backward. The function is_palindrome_number
converts the number to a string and checks if it is equal to its reverse to determine if it’s a palindrome.
Example:
def is_palindrome_number(number):
num_str = str(number)
if num_str == num_str[::-1]:
return "Yes. Given number is a palindrome number"
else:
return "No. Given number is not a palindrome number"
// Example usage:
original_number1 = 121
result1 = is_palindrome_number(original_number1)
print(result1) // Output: "Yes. Given number is a palindrome number"
original_number2 = 125
result2 = is_palindrome_number(original_number2)
print(result2) // Output: "No. Given number is not a palindrome number"
Certainly! num_str[::-1]
is a Python slice notation used to reverse a string. Let me break it down for you:
num_str
: This is a variable that holds a string.[::-1]
: This slice notation instructs Python to create a new string that consists of all characters innum_str
, but with a step of-1
.- The colon
:
before the first empty slot:
indicates that we want to slice the entire string. - The
-1
as the step value means that we want to traverse the string in reverse order.
- The colon
So, when you use num_str[::-1]
, it effectively reverses the characters in the num_str
string. For example:
If num_str
is "12345"
, then num_str[::-1]
will result in "54321"
. It has reversed the original string.
This slicing technique is quite useful for reversing strings in Python.
10. Create a new list from two lists based on conditions in python
Given two lists of numbers, create a new list containing odd numbers from the first list and even numbers from the second list. The function create_new_list
creates a new list by combining odd numbers from the first list and even numbers from the second list based on the given conditions.
Example:
def create_new_list(list1, list2):
result_list = [num for num in list1 if num % 2 != 0] + [num for num in list2 if num % 2 == 0]
return result_list
// Example usage:
list1 = [10, 20, 25, 30, 35]
list2 = [40, 45, 60, 75, 90]
result_list = create_new_list(list1, list2)
print("Result list:", result_list)
Hint: As in the above list comprehension is used, you can learn more from the article, How to Search Items in a Python List.
Conclusion
Congratulations! You’ve completed these Python beginner exercises, and you’re well on your way to becoming a Python pro. By mastering these fundamentals, you’ve built a solid foundation for more advanced Python programming. In this beginner python exercises you get insight how python works and how basic problems python solves.
But wait, there’s more! We’ve prepared some frequently asked questions to help clarify any doubts you may have.
Frequently Asked Questions
Q1: What if I’m stuck on one of the exercises?
Don’t worry; programming can be challenging. Try breaking the problem into smaller parts, and if needed, seek help from Python communities online.
Q2: Can I use Python IDEs for these exercises?
Absolutely! Using Integrated Development Environments like PyCharm or Jupyter Notebook can make coding more convenient.
Q3: Are these exercises suitable for complete beginners?
Yes, these exercises are designed for Python beginners, and they gradually increase in complexity.
Q5: What should I do next to improve my Python skills?
Keep practicing, explore more advanced topics, and work on real-world projects. Python’s versatility offers endless possibilities.