DEV Community

Cover image for Mastering Conditional If Statements in Python With a Real World Example (Guessing Game)
Oluwadamisi Samuel Praise
Oluwadamisi Samuel Praise

Posted on

Mastering Conditional If Statements in Python With a Real World Example (Guessing Game)

If you are new to Python you must have come across some confusing concepts such as the ‘If’ statements, it is one of the most fundamental concepts of python and mastering this concept will help you be more proficient while writing code.

Conditional statements allow you to make decisions based on certain conditions. In programming, the ‘If’ statement is one of the most commonly used conditional statements. By mastering the usage of ‘If’ statements, you can unlock the power to create dynamic and interactive programs.

In this article, we will delve into the concept of conditional ‘If’ statements in Python, using a real-world example of a guessing game.

Understanding If Statements

Conditional statements allow you to control the flow of your program based on certain conditions. The ‘If’ statement, in particular, allows you to execute a block of code only if a given condition is met or true. The if statements follow this general syntax:

`​​if condition:
​​      ​#code to be executed if condition is true  `

Enter fullscreen mode Exit fullscreen mode

The condition can be any expression that evaluates to either ‘True’ or ‘False’. If the condition is ‘True’, the code block within the ‘If’ statement will be executed. Otherwise, it will be skipped.

The following Operators are used to write conditional statements:


`= ​Equal to
>​ Greater than
>= Greater than or equal to
< ​less than
<= ​less than or equal to 
!= ​not equal to
In​: for checking in a list, tuple, dictionary
`
Enter fullscreen mode Exit fullscreen mode

**

Handling Multiple Conditions With elif (else-if) and else

**
When working with conditional statements in python, you often encounter scenarios where you need to evaluate multiple conditions and perform different actions based on the outcomes. Python provides two additional keywords ‘elif’ and ‘else’, to handle such situations effectively.

​When you encounter situations where a single ‘if’ statement is not sufficient to cover all possible outcomes. That’s where ‘elif’(short for else-If) and ‘else’ come into play. ‘else’ can also be used with ’if’ when there are only two conditions.

The 'elif' and 'else' syntax follows this syntax:

`Score = 85;
If score >= 90:
    Grade = 'A'
elif >= 80:
    Grade = 'B'
elif >= 70:
     Grade = 'C'
elif >= 60:
    Grade = 'D'
else:
    Grade = 'F'
print("Your grade is:, Grade)
`
**
Enter fullscreen mode Exit fullscreen mode

Exploring Nested If Statements in Python

**
Nested ‘If’ statements are a way of incorporating one ‘If’ statement inside another. This allows for a more granular and hierarchical decision making process. With nested ‘If’ statements, you can specify conditions, create multiple levels of branching logic.

​​

`If condition:
 ​​​# Code block for condition 1
        If condition 2:
​​          #Code block for condition 2
        ​​​else:
​​​​            #Code block if condition 2 is false
       ​      else:
                 ​​​#Code block if condition 1 is false
`
Enter fullscreen mode Exit fullscreen mode

The inner ‘If’ statement is only executed if the outer ‘If’ statement’s condition is True. If the condition of the inner ‘If’ statement is also true, the code block within it is executed. Otherwise, if the condition of the inner ‘If’ statement is false, the corresponding ‘else’ block is executed.

An important part to note is the Iteration, the different ‘If’ statements and their respective else statements must be aligned in other for the code to be executed seamlessly, wrong iteration will lead to the skipping of an ‘If’ statement or an error in the code execution.
**

Creating a Guessing Game

**
To demonstrate the usage of conditional ‘If’ statements, we will create a simple guessing game. In this game, the computer will generate a random number and the player will try to guess that number within a certain range.

​First, we will set the initial structure of our game. Open your preferred code editor and create a new python file called “Guessing_game.py”. Then we need to import the necessary module for generating random numbers and the module for this in Python is the ‘random’ module:

`import random`
Enter fullscreen mode Exit fullscreen mode

Next, we define the main function of the game (a function is a set of reusable code that performs a specific task) using the def syntax:

`def guessing_game():
 #Game logic goes here
guessing_game()`
Enter fullscreen mode Exit fullscreen mode

Inside the ‘guessing_game’ function, we will implement the game logic using conditional ‘If’ statements.
**

Generating a Random Number

**
​To create the guessing game, we need to generate a random number with specific range. We will use the ‘random’ module to achieve this. Modify the guessing_game function as follows:

`def guessing_game():
    Secret_number = random.randint(1, 100)
    # Game logic goes here
guessing_game()
`
Enter fullscreen mode Exit fullscreen mode

Here, we generate a random integer between 1 and 100 (inclusive) and assign it to the variable ‘computer_guess’. This will be the number the player needs to guess.

**

Accepting User Input

**
Now, the user needs to enter their guess, we can use the ‘input’ function for this purpose. Modify the ‘guessing_game’ function as follows:

`def guessing_game():
    Secret_number = random.randint(1, 100)
    print("Welcome to the Guessing Game")
    Guess = int(input("Enter a number between 1 and 100: "))
    # Game logic goes here
guessing_game()`
Enter fullscreen mode Exit fullscreen mode

The ‘input’ function displays the message “Enter a number between 1 and 100:” and waits for the player to enter their guess. We convert the input to an integer using the ‘int’ function and store it in the variable ‘guess’

**

Using If statement to Check the Guess

**
Now comes the interesting part. We need to check if the player’s guess matches the computer guess. We can use conditional ‘if’ statements to compare the guess and the secret number. Modify the ‘guessing_game’ function as follows:


`def guessing_game():
    Secret_number = random.randint(1, 100)
    print("Welcome to the Guessing Game")
    Guess = int(input("Enter a number between 1 and 100: "))
    if guess == secret_number:
       print("Congratulations! You guessed the correct number.")
     else:
       print("Sorry, you did not guess the correct number,")
guessing_game()`

Enter fullscreen mode Exit fullscreen mode

In the above code, we use an ‘If’ statement to check if the guess is equal to the computer_guess. If it is, the program prints a congratulatory message already specified. Otherwise, it prints a message indicating that the guess was incorrect.

Image description

**

Conclusion

**
Conditional ‘If’ statements are fundamental constructs in Python that enable you to make decisions based on specific conditions. By utilizing ‘If’ statements, you can create dynamic and responsive programs.

In this article, we explored the concept of conditional ‘If’ statements by creating a guessing game as a real world example, delved into Else, Elif(Else-If) and Nested ‘If’ statements. We saw how ‘If’ statements allow us to execute specific code blocks based on the evaluation of a condition. This understanding forms the foundation for more complex decision-making and control flow in Python programs.

Top comments (0)