This Python beginner’s exercise helps you quickly learn and practice basic skills by solving 23 coding questions and challenges, complete with solutions.
Immerse yourself in the practice of Python’s foundational concepts, such as loops, control flow, data types, operators, list, strings, input-output, and built-in functions. This beginner’s exercise is sure to elevate your understanding of Python.
Also, See:
- Python Exercises: A set of 17 topic specific exercises
- Python Quizzes: Solve quizzes to test your knowledge of fundamental concepts.
- Python Basics: Learn the basics of Python to solve this exercise.
- Beginner Python Interview Questions
What questions are included in this exercise?
- This exercise contains 23 coding questions and challenges to solve, ranging from beginner to intermediate difficulty.
- The hints and solutions are provided for each question.
- Tips and essential learning resources accompany each question. These will assist you in solving the exercise and you’ll become more familiar with the basics of Python.
Use Online Code Editor to solve exercises.
This Python exercise covers questions on the following topics:
- Python for loop and while loop
- Python list, set, tuple, dictionary, input, and output
Also, try to solve the basic Python Quiz for beginners
+ Table of Content (23 Exercises)
Exercise 1: Calculate the multiplication and sum of two numbers
Given two integer numbers, write a Python program to return their product only if the product is equal to or lower than 1000. Otherwise, return their sum.
Given 1:
number1 = 20 number2 = 30
Expected Output:
The result is 600
Given 2:
number1 = 40 number2 = 30
Expected Output:
The result is 70
Refer:
Show Hint
- Create a function that takes two numbers as parameters.
- Inside the function:
- Multiply these two numbers.
- Store their product in a variable.
- Check if the product is greater than 1000 using an if condition.
- If the product is greater than 1000, return the product.
- Otherwise (in the
else
block):- Calculate the sum of the two numbers.
- Return the sum.
Show Solution
Exercise 2: Print the Sum of a Current Number and a Previous number
Write Python code to iterate through the first 10 numbers and, in each iteration, print the sum of the current and previous number.
Expected Output:
Printing current and previous number sum in a range(10) Current Number 0 Previous Number 0 Sum: 0 Current Number 1 Previous Number 0 Sum: 1 Current Number 2 Previous Number 1 Sum: 3 Current Number 3 Previous Number 2 Sum: 5 Current Number 4 Previous Number 3 Sum: 7 Current Number 5 Previous Number 4 Sum: 9 Current Number 6 Previous Number 5 Sum: 11 Current Number 7 Previous Number 6 Sum: 13 Current Number 8 Previous Number 7 Sum: 15 Current Number 9 Previous Number 8 Sum: 17
Reference article for help:
Show Hint
- Create a variable called
previous_num
and assign it the value 0. - Next, iterate through the first 10 numbers using the
for
loop andrange()
function. - Next, display the current number (
i
), the previous number, and the addition of both numbers in each iteration of the loop. - Finally, you need to update the
previous_num
for the next iteration. To do this, assign the value of the current number to the previous number (previous_num = i
).
Show Solution
Exercise 3: Print characters present at an even index number
Write a Python code to accept a string from the user and display characters present at an even index number.
For example, str = "PYnative"
. so your code should display ‘P’, ‘n’, ‘t’, ‘v’.
Expected Output:
Orginal String is PYnative
Printing only even index chars
P
n
t
v
Reference article for help: Python Input and Output
Show Hint
- Use the Python
input()
function to accept a string from a user. - Calculate the length of the string using the
len()
function. - Next, iterate through the characters of the string using a loop and the
range()
function. - Use
start = 0
,stop = len(s) - 1
, andstep = 2
. The step is 2 because we want only even index numbers. - In each iteration of the loop, use
s[i]
to print the character present at the current even index number.
Show Solution
Solution 1:
Solution 2: Using list slicing
Exercise 4: Remove first n
characters from a string
Write a Python code to remove characters from a string from 0 to n and return a new string.
Given:
Note: n
must be less than the length of the string.
Show Hint
Use string slicing to get a substring. Think about how you can use the slicing notation [:]
along with the value of n
to select the portion of the string after the first n
characters.
Show Solution
Also, try to solve Python string exercises
Exercise 5: Check if the first and last numbers of a list are the same
Write a code to return True
if the list’s first and last numbers are the same. If the numbers are different, return False
.
Given:
numbers_x = [10, 20, 30, 40, 10]
# output True
numbers_y = [75, 65, 35, 75, 30]
# Output False
Code language: Python (python)
Show Hint
Use list indexing.
- Get the first element of the list.
- Get the last element of the list.
- Compare these two elements using the equality operator (
==
).
Show Solution
Exercise 6: Display numbers divisible by 5
Write a Python code to display numbers from a list divisible by 5
Expected Output:
Given list is [10, 20, 33, 46, 55] Divisible by 5 10 20 55
Show Hint
- Iterate through each number in the list using a
for
loop. - For each number, use the modulo operator (
%
) to find the remainder when divided by 5. If the remainder is 0, it means the number is divisible by 5. In that case, print the number.
Show Solution
Also, try to solve Python list Exercise
Exercise 7: Find the number of occurrences of a substring in a string
Write a Python code to find how often the substring “Emma” appears in the given string.
Given:
str_x = "Emma is good developer. Emma is a writer"
Code language: Python (python)
Expected Output:
Emma appeared 2 times
Show Hint
Use string method count()
.
Show Solution
Solution 1: Use the count()
method
Solution 2: Without the string method
Exercise 8: Print the following pattern
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Refer:
Show Hint
Notice that each row contains the same number repeated, and the number of repetitions increases with the row number.
- You’ll need an outer loop to control the row number (from 1 to 5).
- Inside this loop, you’ll need an inner loop to print the current row’s number the correct number of times. The current row number will also determine how many times the inner loop runs.
Show Solution
Exercise 9: Check Palindrome Number
Write a Python code to check if the given number is a palindrome. A palindrome number reads the same forwards and backward. For example, 545 is a palindrome number.
Expected Output:
original number 121 Yes. given number is palindrome number original number 125 No. given number is not palindrome number
Refer: Python Programs to Check Palindrome Number
Show Hint
Approach 1:
- Take the input number.
- Convert the number to a string.
- Reverse the string.
- Compare the original string with the reversed string. R
- Return
True
if they are the same,False
otherwise.
Approach 2:
- Reverse the given number using while loop and save it in a different variable.
- Use the if condition to check if the original and reverse numbers are identical. If yes, return
True
.
Show Solution
Solution 2:
Solution 1:
def is_palindrome(number):
# Handle negative numbers (they are typically not palindromes)
if number < 0:
return False
# Convert the number to a string
original_string = str(number)
# Reverse the string using slicing
reversed_string = original_string[::-1]
# Compare the original and reversed strings
if original_string == reversed_string:
return True
else:
return False
# Example usage:
print(is_palindrome(121)) # Output: True
print(is_palindrome(123)) # Output: False
Code language: Python (python)
Exercise 10: Merge two lists using the following condition
Given two lists of numbers, write Python code to create a new list containing odd numbers from the first list and even numbers from the second list.
Given:
list1 = [10, 20, 25, 30, 35]
list2 = [40, 45, 60, 75, 90]
Code language: Python (python)
Expected Output:
result list: [25, 35, 40, 60, 90]
Show Hint
- Create an empty list to store the result.
- Iterate through the first list using a for loop; if a number is odd (check using
num % 2 != 0
formula), append it to the new list. - Next, iterate through the second list; if a number is even (remainder when divided by 2 is 0), append it to the new list. Finally, return the newly created list.
Show Solution
Note: Try to solve the Python list exercises
Exercise 11: Get each digit from a number in the reverse order.
For example, If the given integer number is 7536, the output shall be “6 3 5 7“, with a space separating the digits.
Given:
number = 7536
# Output 6 3 5 7
Code language: Python (python)
Refer: Python Programs to Reverse an Integer Number
Show Hint
- You need to isolate the last digit of a number. Use modulo operator (
%
) for this task. Once you have the last digit. - using Integer division (
//
) can help you remove the last digit from the original number. Repeat this process until the number becomes zero. - As you extract each digit, remember to store it (perhaps in a string) in the reverse order you obtained it, separated by spaces.
Show Solution
Use while loop
Exercise 12: Calculate income tax
Calculate income tax for the given income by adhering to the rules below
Taxable Income | Rate (in %) |
---|---|
First $10,000 | 0 |
Next $10,000 | 10 |
The remaining | 20 |
Expected Output:
For example, suppose the income is 45000, and the income tax payable is
10000*0% + 10000*10% + 25000*20% = $6000
Show Solution
Exercise 13: Print multiplication table from 1 to 10
The multiplication table from 1 to 10 is a table that shows the products of numbers from 1 to 10.
Write a code to generates a complete multiplication table for numbers 1 through 10.
Expected Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
See:
Show Hint
Use nested loop, where one loop is placed inside another.
- The outer loop iterates through the rows (numbers 1 to 10).
- The inner loop iterates through the columns (numbers 1 to 10) to calculate and display the product of the numbers.
Show Solution
Exercise 14: Print a downward half-pyramid pattern of stars
* * * * * * * * * * * * * * *
Refer:
Show Hint
- Use an outer loop to iterate through the rows (from the total number of rows down to 1).
- Inside this outer loop, use an inner loop to print the asterisk character.
- The number of times the inner loop runs should be equal to the current row number of the outer loop.
- After the inner loop finishes for each row, print a newline character to move to the next line.
Show Solution
Exercise 15: Get an int value of base raises to the power of exponent
Write a function called exponent(base, exp)
that returns an int value of base raises to the power of exp.
Note here exp
is a non-negative integer, and the base is an integer.
Expected output
Case 1:
base = 2 exponent = 5 2 raises to the power of 5: 32 i.e. (2 *2 * 2 *2 *2 = 32)
Case 2:
base = 5 exponent = 4 5 raises to the power of 4 is: 625 i.e. (5 *5 * 5 *5 = 625)
Show Solution
Exercise 16: Check Palindrome Number
A palindrome number is a number that remains the same when its digits are reversed. In simpler terms, it reads the same forwards and backward. For example 121, 5005.
Write a code to check if given number is palindrome.
See:
Show Hint
Reverse a number and check it with original number.
- Initialize a variable to store the reversed number (set it to 0 initially).
- Use a
while
loop that continues as long as the original number is greater than 0. - Inside the loop:
- Extract the last digit of the original number using the modulo operator (
% 10
). - Update the reversed number: multiply it by 10 and then add the extracted last digit.
- Update the original number by integer division (
// 10
) to remove the last digit.
- Extract the last digit of the original number using the modulo operator (
- After the loop finishes, the reversed number variable will hold the reversed integer.
- Now, check if it is same as original number
Show Solution
Exercise 17: Generate Fibonacci series up to 15 terms
Have you ever wondered about the Fibonacci Sequence? It’s a series of numbers in which the next number is found by adding up the two numbers before it. The first two numbers are 0 and 1.
For example, 0, 1, 1, 2, 3, 5, 8, 13, 21. The next number in this series is 13 + 21 = 34.
Expected output:
Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Refer: Generate Fibonacci Series in Python
Show Hint
- Set
num1 = 0
andnum2 = 1
(first two numbers of the sequence) - Run the loop 15 times
- In each iteration
- print
num1
as the current number of the sequence - Add the last two numbers to get the following number
result = num1 + num2
- update values of
num1
andnum2
. Setnum1 = num2
andnum2 = res
ult
- print
Show Solution
Exercise 18: Check if a given year is a leap year
A leap year is a year in the Gregorian calendar that contains an extra day, making it 366 days long instead of the usual 365. This extra day, February 29th, is added to keep the calendar synchronized with the Earth’s revolution around the Sun.
Rules for leap years: a year is a leap year if it’s divisible by 4, unless it’s also divisible by 100 but not by 400.
Write a code find if a given year is a leap year.
Given:
year1 = 2020
# Output True
year2 = 2025
# Output False
Code language: Python (python)
Show Hint
- Use the modulo operator (
%
) to check for divisibility by 4, 100, and 400. You’ll need to combine these conditions usingif
andelse
statements to cover all the leap year rules. - Write condition in such order in which you check these conditions to ensure you get the correct result.
Show Solution
Exercise: 19: Print Alternate Prime Numbers till 20
A Prime Number is a number that can only be divided by itself and 1 without remainders (e.g., 2, 3, 5, 7, 11).
For example:
All prime numbers from 1 to 20: 2, 3, 5, 7, 11, 13, 17, 19
Alternate prime numbers from 1 to 20:
2, 5, 11, 17
Refer:
Show Hint
- First, identify all the prime numbers within the given range (1 to 20).
- Use this hint to identify prime number: Check divisibility from 2 up to the square root of the number. If divisible by any number in this range, it’s not prime. Handle cases for numbers less than or equal to 1 and the number 2 separately.
- Now, once you have the list of prime numbers, you need to pick every other prime number from that list, starting with the first one using with a specific step.
Show Solution
Exercise 20: Print Reverse Number Pattern
Expected Output:
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
Refer:
Show Hint
In each row, the same number is repeated and in next row the number and count of repetitions changes.
Use a nested loop structure. The outer loop will control which number is being printed (which corresponds to the row number). The inner loop will control how many times that number is printed in the current row.
The number of repetitions relates to the current row number.
Show Solution
Exercise 21: Check if a user-entered string contains any digits using a for loop
Expected Output:
Enter a string: Pynative123Python
The string contains at least one digit.
Enter a string: PYnative
The string does not contain any digits.
Show Hint
- Accept input from user.
- Iterate through each character in the input string using a for loop.
- For each character, check if it is a digit. You can compare its value to the range of digit characters (‘0’ to ‘9’).
- If a digit is found, you can immediately conclude that the string contains digits and return
True
. - If the loop completes without finding any digits, it means the string does not contain any digits. In this case, return
False
Show Solution
Exercise 22: Capitalize the first letter of each word in a string
Expected Output:
str1 = "pynative.com is for python lovers"
# Output Pynative.com Is For Python Lovers
Code language: Python (python)
Show Hint
- Separate the individual words in the string based on whitespace using string
split()
method. - Once you have a list of words, you can iterate through this list and capitalize the first letter of each word using built-in string method
- After capitalizing each word, join them back together into a single string, likely with spaces in between.
Show Solution
Exercise 23: Create a simple countdown timer using a while
loop.
Write a code to create a simple countdown timer of 5 seconds using a while
loop.
Once the timer finishes (when the remaining time reaches zero), print a “Time’s up!” message.
Expected Output:
Time remaining: 5 seconds
Time remaining: 4 seconds
Time remaining: 3 seconds
Time remaining: 2 seconds
Time remaining: 1 seconds
Time's up!
Show Hint
Import time module and use time.sleep()
function inside a while loop.
You’ll need a variable to keep track of the remaining time (initially set to the total countdown duration). The while
loop should continue as long as this remaining time is greater than zero. Inside the loop, you’ll want to:
- Display the current remaining time to the user.
- Pause the program for one second using time module’s
sleep()
function to create the countdown effect. - Decrease the remaining time by one second. Once the loop finishes (when the remaining time reaches zero), you can print a “Time’s up!” message.
Show Solution
Next Steps
I want to hear from you. What do you think of this essential exercise? If you have better alternative answers to the above questions, please help others by commenting on this exercise.
I have shown only 23 questions in this exercise because we have Topic-specific exercises to cover each topic exercise in detail. Please refer to all Python exercises.