Sitemap
Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.

10 If-Else Practice Problems in Python

Ready for some hands on practice examples?

8 min readJul 7, 2024

--

Press enter or click to view image in full size
Photo by Luca Bravo on Unsplash

Learning Python requires practice. This article presents ten if-else Python practice problems to help you gain hands-on experience. Complete with full code solutions and detailed explanations, these exercises are designed to strengthen your understanding of if-else statements.

The if-else statement exemplifies this simplicity, enabling you to incorporate logic into your programs. This article guides you through ten practice exercises, each aimed at beginners.

As the saying goes, practice makes perfect. The more you write code, the more proficient and confident you will become. Whether your goal is to build software, delve into data science, or automate tasks, dedicating time to practice is essential.

Let’s dive in! 🐍💡

“Did you know that you can clap up to 50 times per article? Well now you do! If you found this article helpful, please consider clapping and following me for more insights. Your support is greatly appreciated!” 😊

Interested in more Python content? Feel free to explore my Medium Lists!

The Python if-else Statement

Before diving into the exercises, let’s briefly review how if-else statements work in Python. An if-else statement allows your program to make decisions based on certain conditions. The syntax is straightforward:

  • You provide a condition to evaluate within the if statement.
  • If the condition is true, the corresponding block of code is executed.
  • 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 x is greater than 5, the program prints “x is greater than 5”; otherwise, it prints “x is not greater than 5”. This concept forms the backbone of decision-making in Python programs.

To gain the most benefit from this article, attempt the problems before reading the solutions. Some exercises may have multiple solutions, so consider alternative approaches as well.

Curious about more Python articles? No need to fret — I’ve got you covered! 🐍📚

10 if-else Python Practice Exercises

Exercise 1: Are You Tall?

Exercise: Write a program that asks the user for their height in centimeters. If the height is more than 185 centimeters, print “You are very tall.”

Solution:

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

Explanation: This code stores the user’s input as an integer and checks if it is greater than 185. If so, it prints the message. Notice there is no else block; if the height is less than or equal to 185, nothing happens.

Exercise 2: More Options

Exercise: Write a program that asks the user: “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 checks the user’s input and prints the appropriate response based on whether the input is ‘y’, ’n’, or something else.

Exercise 3: Check If a Character Is in a String

Exercise: Write a program to ask the user for the name of a country that does not contain any lowercase ‘a’ or ‘e’ letters.

  • If the user provides a correct string, print “You won… unless you made this name up!”
  • Otherwise, print “You lost!”

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 checks if the inputted country name contains ‘a’ or ‘e’. If either letter is found, it prints “You lost!”. Otherwise, it prints “You won… unless you made this name up!”.

Exercise 4: Count Letter Frequency in a String

Exercise: Count and print how many times the letter ‘e’ appears in the following 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.
...

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."
...
)
counter = 0
for letter in poem:
if letter == 'e':
counter += 1
print(counter)

Explanation: This code initializes a counter and loops through each letter in the string variable poem. The if statement checks if the current letter is 'e'; if it is, the counter is incremented. Finally, the result is printed.

Exercise 5: Format Recipes

Exercise: Write a Python script that accepts a recipe string from the user and prints an ordered list of sentences.

Solution:

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

Explanation: The solution takes a recipe input, iterates through each character, and formats it into an ordered list by adding numbers before each sentence-ending period.

Exercise 6: Nested if Statements

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

Join Medium for free to get updates from this writer.

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 uses nested if statements to determine if the year is a leap year based on divisibility rules.

Exercise 7: Scrabble

Exercise: Create a function can_build_word(letters_list, word) that checks if the word can be formed using the given list of letters.

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 makes a copy of the letter list to avoid modifying the original, then checks if each letter in the word can be matched and removed from the copy. If any letter cannot be matched, it returns False.

Exercise 8: for Loops and if Statements

Exercise: Write a program that asks for a positive integer and prints all its divisors in ascending order.

Solution:

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

Explanation: This code takes a user input number and iterates from 1 to that number, printing each divisor.

Exercise 9: if Statements and Data Structures

Exercise: Write a function get_character_frequencies() that takes a string and returns a dictionary of character frequencies.

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 creates a dictionary to store character frequencies, converts each character to lowercase, and updates the dictionary accordingly.

Exercise 10: if Statements and Multiple Returns

Exercise: Write a function return_bigger(a, b) that takes two numbers and returns the larger 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: This function uses if-else statements to compare two numbers and return the larger one or 0 if they are equal.

Are you interested in more SQL and Database content? Click here to check out my list on Medium.

Conclusion

Mastering Python is an ongoing journey that requires consistent practice and engagement with a variety of problems. These ten if-else exercises are just a starting point to enhance your understanding of conditional statements in Python. By solving these exercises, you not only familiarize yourself with basic syntax but also develop problem-solving skills crucial for more advanced programming challenges. The importance of conditional statements cannot be overstated; they form the backbone of decision-making in software, enabling your programs to respond dynamically to different inputs and conditions.

Beyond these exercises, it is vital to immerse yourself in a comprehensive learning ecosystem. Utilize diverse resources such as books, blogs, video tutorials, and interactive courses. Participating in coding communities, like Stack Overflow or GitHub, can provide additional support and inspiration. Engaging with fellow learners and experienced developers allows you to gain new perspectives, share knowledge, and solve problems collaboratively. These interactions are invaluable for reinforcing your learning and staying motivated on your coding journey.

Remember, the key to becoming proficient in Python or any programming language is practice and persistence. The exercises and solutions presented here are extracted from various interactive online courses designed to build your skills progressively. By continuously challenging yourself with new problems and seeking out opportunities to apply your knowledge, you will develop a deeper understanding and greater confidence in your programming abilities. So, keep coding, stay curious, and enjoy the process of learning.

Happy coding!

Eager to enhance your data manipulation prowess? Dive into NumPy for numerical operations and Pandas for data analysis! Supercharge your data science toolkit and computational skills with these powerful Python libraries!

Press enter or click to view image in full size
Photo by Call Me Fred on Unsplash

Final Words:

Thank you for taking the time to read my article.

This article was first published on medium by CyCoderX.

Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!

Join me as we explore the exciting world of tech, data and beyond!

For similar articles and updates, feel free to explore my Medium profile

If you enjoyed this article, consider following for future updates.

Interested in Python content and tips? Click here to check out my list on Medium.

Interested in more SQL, Databases and Data Engineering content? Click here to find out more!

Happy Coding!

What did you think about this article? If you found it helpful or have any feedback, I’d love to hear from you in the comments below!

Please consider supporting me by:

  1. Clapping 50 times for this story
  2. Leaving a comment telling me your thoughts
  3. Highlighting your favorite part of the story

Let me know in the comments below … or above, depending on your device 🙃

In Plain English 🚀

Thank you for being a part of the In Plain English community! Before you go:

--

--

CyCoderX
CyCoderX

Written by CyCoderX

Machine Learning & Data Engineer | Data Science | Python & SQL | AI | Software Developer | Azure & AWS Cloud Specialist | Blogger simplifying Big Data & Trends

Python in Plain English
Python in Plain English

Published in Python in Plain English

New Python content every day. Follow to join our 3.5M+ monthly readers.