What are conditional statements?

Conditional statements are used in programming to execute certain blocks of code based on certain conditions. In other words, these statements allow you to make decisions in your program based on the value of some variable or input.

In Python, there are two types of conditional statements:

  1. If statements: These statements are used when you want to execute a block of code if a certain condition is true.
  2. If-else statements: These statements are used when you want to execute a block of code if a certain condition is true, and another block of code if that condition is false.

Now, let's take a look at some sample codes that use conditional statements.

Sample Code 1 (Easy)

In this sample code, we will use an if statement to check whether a number is even or odd.

# Program to check whether a number is even or odd

number = 6

if number % 2 == 0:
    print("The number is even.")

Output: The number is even.

Step-by-step instructions:

  1. We start by defining a variable called "number" and assigning it the value of 6.
  2. We use an if statement to check whether the value of "number" is even or odd. We do this by using the modulus operator (%), which gives us the remainder of the division of "number" by 2. If the remainder is 0, then the number is even.
  3. If the condition in the if statement is true, we print the message "The number is even." to the console.

Sample Code 2 (Medium)

In this sample code, we will use an if-else statement to check whether a person is old enough to vote.

# Program to check whether a person is old enough to vote

age = 16

if age >= 18:
    print("You are old enough to vote.")
else:
    print("You are not old enough to vote.")

Output: You are not old enough to vote.

Step-by-step instructions:

  1. We start by defining a variable called "age" and assigning it the value of 16.