Conditional Statements

Conditional Statements


In this chapter, we will cover conditional statements and their uses. The format of conditional statement is shown below

if(condition):
    do something

If you look carefully, the second line is indented. Python works on indentation rather than brackets. So, when you want some code to be executed under some condition or block then you should intend it.

Now, let's find if a number is odd or even.

a = input("Enter a number: ")
if a % 2 == 0:
    print("Number is even")
else:
    print("Number is odd")

'%' is the modulo operator. The modulo operation finds the remainder after division of one number by another.


Lets try us try to predict a random number.

import random
random_number = random.randint(1, 10)
our_guess = int(input("Guess a number between 1 and 10: "))
if our_guess == random_number:
    print("Your Guess is Correct! Congratulations")
else:
    print("Your Guess is Incorrect! The number is %d. Try Again" %(random_number))


Now, lets add more features to the same problem. What happens if a user enters a number more than 10.

import random
random_number = random.randint(1, 10)
our_guess = int(input("Guess a number between 1 and 10: "))
if our_guess > 10 or our_guess < 0:
    print("Please enter a number between 1 and 10")
    our_guess = int(input("Guess a number between 1 and 10: "))
if our_guess == random_number:
    print("Your Guess is Correct! Congratulations")
else:
    print("Your Guess is Incorrect! The number is %d. Try Again" %(random_number))

Try to complete the Dice Simulator Game by using to same logic.