It looks like you're using Internet Explorer 11 or older. This website works best with modern browsers such as the latest versions of Chrome, Firefox, Safari, and Edge. If you continue with this browser, you may see unexpected results.

# Python for Basic Data Analysis: 1.13 Conditional statements (if-elif-else)

Get started on your learning journey towards data science using Python. Equip yourself with practical skills in Python programming for the purpose of basic data manipulation and analysis.

## if-elif-else

#### If statements

We can use if statements when we want the code to do something when a condition is met.

Sequence of an if statement:

Step 1 Evaluate condition • If  True  , execute action • If  False , skip action

Syntax

```x = 3
if x >= 2:
print("x is bigger than or equal to 2")```

Example

#### If-else statements

We can use if-else statements when we want the code to do something else if the condition fails.

Sequence of an if-else statement:

Step 1 Evaluate condition • If  True  , execute action • If  False , execute another action

Syntax

```x = 30

if x >= 50:
print("x bigger than or equals to 50")
else:
print("x is a number smaller than 50")```

Examples

#### If-elif-else statements

We can use the if-elif-else statement to tell Python to try a different condition if the previous conditions were not met.

Sequence of an if-elif-else statement:

Step 1 • If the first condition is  True , then execute the first action • If it is  False , then test for the second condition • If the second condition is  True , then execute the second action • If it is  False , execute the final else action

Syntax

```x = 10
if x > 20:
print("x is bigger than 10.")
elif x = 20:
print("x is equals to 20.")
else:
print("x is neither bigger than 10 or equal to 20.")
```

Example

## Exercises

1. If - Assign 10 to x. If x is bigger than 0, print "x is a positive number".

2. If-else - Assign -50 to y. If x is bigger than 0, print "x is a positive number". Else, print "x is a negative number".

3. If-elif-else - Assign 0 to z. If x is bigger than 0, print "x is a positive number". Else if x is zero, print "x is 0". Else, print "x is a negative number".