Back to articles list Articles
13 minutes read

10 if-else Practice Problems in Python

If you're trying to learn Python, you need to practice! These ten if-else Python practice problems provide you some hands-on experience. And don’t worry – we’ve provided full code solutions and detailed explanations!

Python is particularly good for beginners to learn. Its clear syntax can be read almost as clearly as a normal sentence. The if-else statement is a good example of this; it lets you build logic into your programs. This article will walk you through ten if-else practice exercises in Python. Each one is specifically designed for beginners, helping you hone your understanding of if-else statements.

The exercises in this article are taken directly from our courses, including Python Basics: Part 1. This course helps absolute beginners understand computer programming with Python; if you’ve never written a line of code, this course is a great place to start.

As the saying goes, practice makes perfect. Learning Python is no exception. As we discuss in Different Ways to Practice Python, doing online courses is a great way to practice a variety of topics. The more you practice writing code, the more comfortable and confident you'll become in your abilities. So – whether you aim to build your own software, delve into data science, or automate mundane tasks – dedicating time to practice is key.

The Python if-else Statement

Before we dive into the exercises, let's briefly discuss the workings of if-else statements in Python. An if-else statement allows your program to make decisions based on certain conditions. The syntax is straightforward:

  1. You provide a condition to evaluate within the if
  2. If that condition is true, the corresponding block of code is executed.
  3. If the condition is false, the code within the optional else block is executed instead.

Here's a simple example:

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is not greater than 5")

In this example, if the value of x is greater than 5, the program will print "x is greater than 5"; otherwise, it will print "x is not greater than 5".

This concept forms the backbone of decision-making in Python programs.

To get the most benefit from this article, attempt the problems before reading the solutions. Some of these exercises will have several possible solutions, so also try to think about alternative ways to solve the same problem. Let’s get started.

10 if-else Python Practice Exercises

Exercise 1: Are You Tall?

Exercise: Write a program that will ask the user for their height in centimeters. Use the input() built-in function to do this. If the height is more than 185 centimeters, print the following line of code:

You are very tall.

Solution:

height = input('What is your height in centimeters? ')
if int(height) > 185:
    print('You are very tall')

Explanation: This is a similar syntax to the above template example. The height variable stores the user input as an integer and tests if it’s greater than 185 cm. If so, the message is printed. Notice there is no else; this means if the height is less than or equal to 185, nothing happens.

Exercise 2: More Options

Exercise: Write a program that will ask the user the following question:

Is Sydney the capital of Australia? 
  • If the user answers y, print: Wrong! Canberra is the capital!
  • If the user answers n, print: Correct!
  • If the user answers anything else, print: I do not understand your answer!

Solution:

answer = input('Is Sydney the capital of Australia? ')
if answer == 'y':
    print('Wrong! Canberra is the capital!')
elif answer == 'n':
    print('Correct!')
else:
    print('I do not understand your answer!')

Explanation: The if statement can be extended with an elif (i.e. else if) to check any answer that returns False to the first condition. If the elif statement also returns False, the indented block under the else is executed.

Exercise 3: Check If a Character Is in a String

Exercise: Write a program to ask the user to do the following:

  • Provide the name of a country that does not contain any lowercase a or e letters. (Use the prompt: The country is: )
  • If the user provides a correct string (i.e. one with no a or e inside it), print: You won... unless you made this name up!
  • Otherwise, print: You lost!

(By the way, possible answers include Hong Kong, Cyprus, and Togo.)

Solution:

country = input('The country is: ')
if 'a' in country or 'e' in country:
    print('You lost!')
else:
    print('You won... unless you made this name up!')

Explanation: This code prompts the user to input a country name using the built-in input() function. Then, it checks if the letters 'a' or 'e' is present in the inputted country name using the in operator. If either letter is found, it prints "You lost!". Otherwise, it prints "You won... unless you made this name up!" using the else statement.

Exercise 4: Count Letter Frequency in a String

Exercise: The letter e is said to be the most frequent letter in the English language. Count and print how many times this letter appears in the poem below:

John Knox was a man of wondrous might,
And his words ran high and shrill,
For bold and stout was his spirit bright,
And strong was his stalwart will.
Kings sought in vain his mind to chain,
And that giant brain to control,
But naught on plain or stormy main
Could daunt that mighty soul.
John would sit and sigh till morning cold
Its shining lamps put out,
For thoughts untold on his mind lay hold,
And brought but pain and doubt.
But light at last on his soul was cast,
Away sank pain and sorrow,
His soul is gay, in a fair to-day,
And looks for a bright to-morrow.

(Source: "Unidentified," in Current Opinion, July 1888)

Solution:

poem = ('John Knox was a man of wondrous might,'
'And his words ran high and shrill,'
'For bold and stout was his spirit bright,'
'And strong was his stalwart will.'

'Kings sought in vain his mind to chain,'
'And that giant brain to control,'
'But naught on plain or stormy main'
'Could daunt that mighty soul.'

'John would sit and sigh till morning cold'
'Its shining lamps put out,'
'For thoughts untold on his mind lay hold,'
'And brought but pain and doubt.'

'But light at last on his soul was cast,'
'Away sank pain and sorrow,'
'His soul is gay, in a fair to-day,'
'And looks for a bright to-morrow.')

counter = 0
for letter in poem:
  if letter == 'e':
    counter = counter + 1

print(counter)

Explanation: The solution starts by initializing a counter with the value of 0. Then a for loop is used to loop through every letter in the string variable poem. The if statement tests if the current letter is an e; if it is, the counter is incremented by 1. Finally, the result of the counter is printed. Note that there is no else needed in this solution, since nothing should happen if the letter is not an e.

Exercise 5: Format Recipes

Exercise: Anne loves cooking and she tries out various recipes from the Internet. Sometimes, though, she finds recipes that are written as a single paragraph of text. For instance:

Cut a slit into the chicken breast. Stuff it with mustard, mozzarella and cheddar. Secure the whole thing with rashers of bacon. Roast for 20 minutes at 200C.

When you're in the middle of cooking, such a paragraph is difficult to read. Anne would prefer an ordered list, like this:

  1. Cut a slit into the chicken breast.
  2. Stuff it with mustard, mozzarella and cheddar.
  3. Secure the whole thing with rashers of bacon.
  4. Roast for 20 minutes at 200C.

Write a Python script that accepts a recipe string from the user ('Paste your recipe: ') and prints an ordered list of sentences, just like in the example above.

Each sentence of both the input and output should end with a single period.

Solution:

recipe = input('Paste your recipe: ')
counter = 1
ordered_list = str(counter) + '. '
for letter in recipe:
    if letter == '.':
      counter += 1
      ordered_list += '.\n'
      ordered_list += str(counter)
      ordered_list += '.'
    else:
      ordered_list += letter
no = len(str(counter))
print(ordered_list[0:-1-no])

Explanation: The solution takes a recipe input from the user with input(), then iterates through each character in the recipe. Whenever it encounters a period ('.'), it increments a counter, adds a new line character ('\n') and the incremented counter followed by a period to an ordered list. If it encounters any other character, it simply adds that character to the ordered list. Finally, it calculates the length of the counter, removes the last part of the ordered list to exclude the unnecessary counter, and prints the modified ordered list, which displays the recipe with numbered steps.

Exercise 6: Nested if Statements

Exercise: A leap year is a year that consists of 366 (not 365) days. It occurs roughly every four years. More specifically, a year is considered leap if it is either divisible by 4 but not by 100 or it is divisible by 400.

Write a program that asks the user for a year and replies with either leap year or not a leap year.

Solution:

year = int(input('Provide a year: '))

if (year % 4) == 0:
    if (year % 100) == 0:
        if (year % 400) == 0:
            print('leap year')
        else:
            print('not a leap year')
    else:
        print('leap year')
 else:
     print('not a leap year')

Explanation: This program takes a year from the user as input. It checks if the year is divisible by 4. If it is, it then checks if the year is divisible by 100. If it is, it further checks if the year is divisible by 400. If it is, it prints 'leap year' because it satisfies all the conditions for a leap year. This is all achieved with nesting.

If it's divisible by 4, but not by 100, or if it’s not divisible by 400, the program prints 'not a leap year'. If the year is not divisible by 100, it directly prints 'leap year' because it satisfies the basic condition for a leap year (being divisible by 4). If the year is not divisible by 4, it prints 'not a leap year'.

Exercise 7: Scrabble

Exercise: Create a function called can_build_word(letters_list, word) that takes a list of letters and a word. The function should return True if the word uses only the letters from the list.

Like in real Scrabble, you cannot use one tile twice in the same word. For example, if a list of letters contains only one 'a', ‘banana’ returns False. The function should also return False if the word contains any letters not in the list.

For example …

can_build_word(['a', 'b', 'e', 'g', 'l', 'r', 'z'], 'glare')

… should return True. On the other hand …

can_build_word(['a', 'i', 'n', 's', 'f', 'q', 'y'], 'sniff')

… should return False because there is only one 'f'.

One thing to keep in mind: Neither the provided letter list nor the word should be changed by your function. It may be tempting to remove letters from the letters list to remove the used tiles. This should not be the case. Instead, you should copy the passed list. Simply use the list() function and pass it another list:

word_list_copy = list(word_list)

This way we can safely operate on a copy of the list without changing the contents of the original list.

Solution:

def can_build_word(letters_list, word):
    letters_list_copy = list(letters_list)
    for letter in word:
        if letter in letters_list_copy:
            letters_list_copy.remove(letter)
        else:
            return False
return True

Explanation: The function starts by making a copy of the list of letters to avoid modifying the original. Then, it iterates through each letter in the word. For each letter, it checks if that letter exists in the list copy. If it does, it removes that letter from the copy, which ensures each letter is used only once.

If the letter doesn't exist in the copy of the letters list, it means the word cannot be formed using the available letters; it returns False. If all the letters in the word can be found and removed from the list copy, it means the word can indeed be formed; it returns True.

If you are looking for additional material to help you learn how to work with Python lists, our article 12 Beginner-Level Python List Exercises with Solutions has got you covered.

Exercise 8: for Loops and if Statements

Exercise: Write a program that asks for a positive integer and prints all of its divisors, one by one, on separate lines in ascending order.

A divisor is a number that divides a particular number with no remainder. For example, the divisors of 4 are 1, 2, and 4.

To check if a is a divisor of b, you can use the modulo operator %. a % b returns the remainder of dividing a by b. For example, 9 % 2 is 1 because 9 = (4 * 2) + 1, and 9 % 3 is 0 because 9 divides into 3 with no remainder. If a % b == 0, then b is a divisor of a.

Solution:

number = int(input("Please enter a number: "))
for i in range(1, number + 1):
    if number % i == 0:
        print(i)

Explanation: This solution takes an input number from the user and then iterates through numbers from 1 to that input number (inclusive). For each number i in this range, it checks if the input number is divisible by i with no remainder (number % i == 0). If the condition is satisfied, it means that i is a factor of the input number.

Looping is another important skill in Python. This problem could also be solved with a while loop. Take a look at 10 Python Loop Exercises with Solutions to learn more about for and while loops.

Exercise 9: if Statements and Data Structures

Exercise: Write a function named get_character_frequencies() that takes a string as input and returns a dictionary of lowercase characters as keys and the number of their occurrences as values. Ignore the case of a character.

Solution:

def get_character_frequencies(word):
    freq_dict = {}
    for character in word:
        character = character.lower()
        if character not in freq_dict:
            freq_dict[character] = 1
        else:
            freq_dict[character] += 1
    return freq_dict

Explanation: This function initializes an empty dictionary (freq_dict) to store the frequencies of characters. It iterates through each character in the input word using a for loop. Within the loop, it converts each character to lowercase using the lower() method; this ensures case-insensitive counting.

The program checks if the lowercase character is already a key in the dictionary. If it's not, it adds the character as a key and sets its frequency to 1. If it is already a key, it increments the frequency count for that character by 1 and returns the dictionary.

If you’re not familiar with how Python dictionaries work, Top 10 Python Dictionary Exercises for Beginners will give you experience working with this important data structure.

Exercise 10: if Statements and Multiple Returns

Exercise: Write a function named return_bigger(a, b) that takes two numbers and returns the bigger one. If the numbers are equal, return 0.

Solution:

def return_bigger(a, b):
    if a > b:
        return a
    elif b > a:
        return b
    else:
        return 0

Explanation: When using if statements in a function, you can define a return value in the indented block of code under the if-else statement. This makes your code simpler and more readable – another great example of the clear syntax which makes Python such an attractive tool for all programmers.

Do You Want More Python Practice Exercises?

Learning anything new is a challenge. Relying on a variety of resources is a good way to get a broad background. Read some books and blogs to get a theoretical understanding, watch videos online, take advantage of the active Python community on platforms like Stack Overflow. And most importantly, do some hands-on practice. We discuss these points in detail in What’s the Best Way to Practice Python?

The Python practice exercises and solutions shown here were taken directly from several of our interactive online courses, including Python Basics Practice, Python Practice: Word Games, and Working with Strings in Python. The courses build up your skills and knowledge, giving you exposure to a variety of topics.

And if you’re already motivated to take your skills to the next level, have a go at another 10 Python Practice Exercises for Beginners with Solutions. Happy coding!