PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Basic Exercise for Beginners

Python Basic Exercise for Beginners

Updated on: April 30, 2025 | 522 Comments

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)

Table of contents

  • Exercise 1: Calculate the multiplication and sum of two numbers
  • Exercise 2: Print the Sum of a Current Number and a Previous number
  • Exercise 3: Print characters present at an even index number
  • Exercise 4: Remove first n characters from a string
  • Exercise 5: Check if the first and last numbers of a list are the same
  • Exercise 6: Display numbers divisible by 5
  • Exercise 7: Find the number of occurrences of a substring in a string
  • Exercise 8: Print the following pattern
  • Exercise 9: Check Palindrome Number
  • Exercise 10: Merge two lists using the following condition
  • Exercise 11: Get each digit from a number in the reverse order.
  • Exercise 12: Calculate income tax
  • Exercise 13: Print multiplication table from 1 to 10
  • Exercise 14: Print a downward half-pyramid pattern of stars
  • Exercise 15: Get an int value of base raises to the power of exponent
  • Exercise 16: Check Palindrome Number
  • Exercise 17: Generate Fibonacci series up to 15 terms
  • Exercise 18: Check if a given year is a leap year
  • Exercise: 19: Print Alternate Prime Numbers till 20
  • Exercise 20: Print Reverse Number Pattern
  • Exercise 21: Check if a user-entered string contains any digits using a for loop
  • Exercise 22: Capitalize the first letter of each word in a string
  • Exercise 23: Create a simple countdown timer using a while loop.
  • Next Steps

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:

  • Accept user input in Python
  • Calculate an Average in Python
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
def multiplication_or_sum(num1, num2):
    # calculate product of two number
    product = num1 * num2
    # check if product is less then 1000
    if product <= 1000:
        return product
    else:
        # product is greater than 1000 calculate sum
        return num1 + num2

# first condition
result = multiplication_or_sum(20, 30)
print("The result is", result)

# Second condition
result = multiplication_or_sum(40, 30)
print("The result is", result)Code language: Python (python)

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:

  • Python range() function
  • Calculate sum and average in Python
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 and range() 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
print("Printing current and previous number and their sum in a range(10)")
previous_num = 0

# loop from 1 to 10
for i in range(1, 11):
    x_sum = previous_num + i
    print("Current Number", i, "Previous Number ", previous_num, " Sum: ", x_sum)
    # modify previous number
    # set it to the current number
    previous_num = iCode language: Python (python)

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, and step = 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:

# accept input string from a user
word = input('Enter word ')
print("Original String:", word)

# get the length of a string
size = len(word)

# iterate a each character of a string
# start: 0 to start with first character
# stop: size-1 because index starts with 0
# step: 2 to get the characters present at even index like 0, 2, 4
print("Printing only even index chars")
for i in range(0, size - 1, 2):
    print("index[", i, "]", word[i])Code language: Python (python)

Solution 2: Using list slicing

# accept input string from a user
word = input('Enter word ')
print("Original String:", word)

# using list slicing
# convert string to list
# pick only even index chars
x = list(word)
for i in x[0::2]:
    print(i)Code language: Python (python)

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:

def remove_chars(word, n):
    # write your code

print("Removing characters from a string")
print(remove_chars("pynative", 4)) 
# output 'tive' first four characters are removed

print(remove_chars("pynative", 2)) 
# output 'native'Code language: Python (python)

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
def remove_chars(word, n):
    print('Original string:', word)
    x = word[n:]
    return x

print("Removing characters from a string")
print(remove_chars("pynative", 4))
print(remove_chars("pynative", 2))Code language: Python (python)

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 FalseCode 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
def first_last_same(numberList):
    print("Given list:", numberList)
    
    first_num = numberList[0]
    last_num = numberList[-1]
    
    if first_num == last_num:
        return True
    else:
        return False

numbers_x = [10, 20, 30, 40, 10]
print("result is", first_last_same(numbers_x))

numbers_y = [75, 65, 35, 75, 30]
print("result is", first_last_same(numbers_y))Code language: Python (python)

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
num_list = [10, 20, 33, 46, 55]
print("Given list:", num_list)
print('Divisible by 5:')
for num in num_list:
    if num % 5 == 0:
        print(num)Code language: Python (python)

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

str_x = "Emma is good developer. Emma is a writer"
# use count method of a str class
cnt = str_x.count("Emma")
print(cnt)
Code language: Python (python)

Solution 2: Without the string method

def count_emma(statement):
    print("Given String: ", statement)
    count = 0
    for i in range(len(statement) - 1):
        count += statement[i: i + 4] == 'Emma'
    return count

count = count_emma("Emma is good developer. Emma is a writer")
print("Emma appeared ", count, "times")Code language: Python (python)

Exercise 8: Print the following pattern

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
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
for num in range(10):
    for i in range(num):
        print (num, end=" ") # print number
    # new line after each row to display pattern correctly
    print("\n")Code language: Python (python)

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:
def palindrome(number):
    print("original number", number)
    original_num = number
    
    # reverse the given number
    reverse_num = 0
    while number > 0:
        reminder = number % 10
        reverse_num = (reverse_num * 10) + reminder
        number = number // 10

    # check numbers
    if original_num == reverse_num:
        print("Given number palindrome")
    else:
        print("Given number is not palindrome")

palindrome(121)
palindrome(125)Code language: Python (python)

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: FalseCode 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
def merge_list(list1, list2):
    result_list = []
    
    # iterate first list
    for num in list1:
        # check if current number is odd
        if num % 2 != 0:
            # add odd number to result list
            result_list.append(num)
    
    # iterate second list
    for num in list2:
        # check if current number is even
        if num % 2 == 0:
            # add even number to result list
            result_list.append(num)
    return result_list

list1 = [10, 20, 25, 30, 35]
list2 = [40, 45, 60, 75, 90]
print("result list:", merge_list(list1, list2))Code language: Python (python)

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 7Code 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

number = 7536
print("Given number", number)
while number > 0:
    # get the last digit
    digit = number % 10
    # remove the last digit and repeat the loop
    number = number // 10
    print(digit, end=" ")Code language: Python (python)

Exercise 12: Calculate income tax

Calculate income tax for the given income by adhering to the rules below

Taxable IncomeRate (in %)
First $10,0000
Next $10,00010
The remaining20

Expected Output:

For example, suppose the income is 45000, and the income tax payable is

10000*0% + 10000*10%  + 25000*20% = $6000
Show Solution
income = 45000
tax_payable = 0
print("Given income", income)

if income <= 10000:
    tax_payable = 0
elif income <= 20000:
    # no tax on first 10,000
    x = income - 10000
    # 10% tax
    tax_payable = x * 10 / 100
else:
    # first 10,000
    tax_payable = 0

    # next 10,000 10% tax
    tax_payable = 10000 * 10 / 100

    # remaining 20%tax
    tax_payable += (income - 20000) * 20 / 100

print("Total tax to pay is", tax_payable)Code language: Python (python)

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:

  • Nested loops in Python
  • Create Multiplication Table in Python
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
for i in range(1, 11):
    for j in range(1, 11):
        print(i * j, end=" ")
    print("\t\t")Code language: Python (python)

Exercise 14: Print a downward half-pyramid pattern of stars

* * * * *  
* * * *  
* * *  
* *  
*

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
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
for i in range(6, 0, -1):
    for j in range(0, i - 1):
        print("*", end=' ')
    print(" ")Code language: Python (python)

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
def exponent(base, exp):
    num = exp
    result = 1
    while num > 0:
        result = result * base
        num = num - 1
    print(base, "raises to the power of", exp, "is: ", result)

exponent(5, 4)Code language: Python (python)

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:

  • Python Programs to Check Palindrome Number
  • Python Programs to Reverse an Integer Number
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.
  • After the loop finishes, the reversed number variable will hold the reversed integer.
  • Now, check if it is same as original number
Show Solution
def is_palindrome_while_loop(number):
  
    original_number = number
    reversed_number = 0

    while number > 0:
        remainder = number % 10
        reversed_number = (reversed_number * 10) + remainder
        number //= 10

    return original_number == reversed_number

# Example usage:
print(is_palindrome_while_loop(121))   # Output: True
print(is_palindrome_while_loop(123))   # Output: FalseCode language: Python (python)

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 and num2 = 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 and num2. Set num1 = num2 and num2 = result
Show Solution
# first two numbers
num1, num2 = 0, 1

print("Fibonacci sequence:")
# run loop 15 times
for i in range(15):
    # print next number of a series
    print(num1, end="  ")
    # add last two numbers to get next number
    res = num1 + num2

    # update values
    num1 = num2
    num2 = resCode language: Python (python)

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 FalseCode 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 using if and else 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
def is_leap_year(year):
  """
  Returns:
    True if the year is a leap year, False otherwise.
  """
  print("Year", year)
  if year % 4 == 0:
    if year % 100 == 0:
      if year % 400 == 0:
        return True
      else:
        return False
    else:
      return True
  else:
    return False

# check
print(is_leap_year(2020)) # True
print(is_leap_year(2025)) # FalseCode language: Python (python)

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:

  • Python Programs to Check Prime Number
  • Python Programs to Print alternate Prime Numbers
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
# Function to check if a number is prime
def is_prime(num):
    if num < 2:
        return False
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return True

# Set N
n = 20
primes = []  # List to store all prime numbers
for num in range(2, n + 1):
    if is_prime(num):
        primes.append(num)

# Printing all prime numbers
print(f'All prime numbers from 1 to {n}: {primes}')

# Printing alternate prime numbers from the list
print(f'Alternate prime numbers from 1 to {n}:')

for i in range(0, len(primes), 2):  # Step by 2 to get alternate primes
    print(primes[i])Code language: Python (python)

Exercise 20: Print Reverse Number Pattern

Expected Output:

1 1 1 1 1 
2 2 2 2
3 3 3
4 4
5

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
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
def print_pattern(rows):  
  for i in range(1, rows + 1):
    for j in range(rows - i + 1):
      print(i, end=" ")
    print()

# Print the pattern with 5 rows
print_pattern(5)Code language: Python (python)

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
def contains_digits(text):
  
  for char in text:
    if '0' <= char <= '9':
      return True  # Found a digit, so return True immediately
  return False  # No digits found after checking all characters

# Get input from the user
user_string = input("Enter a string: ")

if contains_digits(user_string):
  print("The string contains at least one digit.")
else:
  print("The string does not contain any digits.")Code language: Python (python)

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 LoversCode 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
def capitalize_words(text):
  
  words = text.split()  # Split the string into a list of words
  capitalized_words = [word.capitalize() for word in words]  # Capitalize each word
  return " ".join(capitalized_words)  # Join the capitalized words back into a string

# Get input from the user
str1 = "pynative.com is for python lovers"

capitalized_string = capitalize_words(str1)
print("Capitalized string:", capitalized_string)Code language: Python (python)

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:

  1. Display the current remaining time to the user.
  2. Pause the program for one second using time module’s sleep() function to create the countdown effect.
  3. 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
import time

def countdown_timer(seconds):
  
  while seconds > 0:
    print(f"Time remaining: {seconds} seconds")
    time.sleep(1)  # Pause for 1 second
    seconds -= 1

  print("Time's up!")

# Get the countdown duration from the user
duration = 5
countdown_timer(duration)Code language: Python (python)

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.

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement