Sometimes we want our code to be executed conditionally, not every time. Or, we may want to define several different paths of execution depending on some condition.
We use if to make conditions. The condition is followed by a colon and the block of code which follows is indented.
We can add more conditions with elif. We can add an else block. It’s executed if the condition is not met. There may be only one else statement, but there may be any number of elif statements. As soon as an elif condition is met, its conditional block is executed and the following elif statements are ignored.
Example:
word = input("Enter a word: ")
if len(word) > 10:
print("This word is too long.")
print("I can't accept it.")
elif len(word) > 7: # block of code (colon + indentation)
print("It's a long word.") # indentation
print("I prefer shorter words.")
elif len(word) > 4: # optional
print("It's a medium-length word.")
print("I can accept it.")
else:
print("It's a short word.")
print("I like short words.")
print("I'm satisfied.")
Possible outputs:
Enter a word: unbelievable
This word is too long.
I can't accept it.
or:
Enter a word: frost
It's a medium-length word.
I can accept it.
etc.
We can use any comparison operator in the condition. We use a double equals sign for equality, because a single equals sign is used for assigning values to variables. Here are all the comparison operators we can use:
== | equal to |
!= | not equal to |
> | greater than |
< | less than |
>= | greater than or equal to |
<= | less than or equal to |
Example:
number1 = 4
number2 = 3
if number1 == number2:
print("The numbers are equal.")
if number1 * number2 != 20:
print("The product of the numbers is not 20.")
if number1 + number2 < 10:
print("The numbers are small.")
Output:
The product of the numbers is not 20.
The numbers are small.
Table of Contents
QUIZ
1. An if-condition is followed by a: |
A) colon |
B) semicolon |
C) open parenthesis |
2. We can add more conditions with: |
A) else if |
B) elsif |
C) elif |
3. The comparison operator ‘not equal to’ is written as: |
A) <> |
B)!= |
C)!== |
4. The comparison operator ‘greater than or equal to’ is written as: |
A) >> |
B) >= |
C) >== |
TRUE OR FALSE?
1) A conditional block is only executed if the condition is true. |
2) There may be any number of else statements in a conditional statement. |
3) If an elif condition is met, its conditional block is executed and the following elif statements are ignored. |
4) All statements within a block must be indented the same number of spaces. |
5) Indentation in Python is just a matter of style, but it’s not obligatory. |
WHAT’S THE OUTPUT?
1)
>>> a = 2 * 5
>>> if a < 4:
... print("hello")
...
2)
>>> x = "abc"
>>> if x == "abc":
... print("yes")
... else:
... print("no")
...
3)
>>> z = 8
>>> if z <= 8:
... print("OK")
...
SOLUTION
QUIZ
1. An if-condition is followed by a: |
A) colon |
B) semicolon |
C) open parenthesis |
2. We can add more conditions with: |
A) else if |
B) elsif |
C) elif |
3. The comparison operator ‘not equal to’ is written as: |
A) <> |
B)!= |
C)!== |
4. The comparison operator ‘greater than or equal to’ is written as: |
A) >> |
B) >= |
C) >== |
TRUE OR FALSE?
1) A conditional block is only executed if the condition is true. True |
2) There may be any number of else statements in a conditional statement. False |
3) If an elif condition is met, its conditional block is executed and the following elif statements are ignored. True |
4) All statements within a block must be indented the same number of spaces. True |
5) Indentation in Python is just a matter of style, but it’s not obligatory. False |
WHAT’S THE OUTPUT?
1) >>> a = 2 * 5 >>> if a < 4: … print(“hello”) … Output: (empty output because the condition was not met) |
2) >>> x = “abc” >>> if x == “abc”: … print(“yes”) … else: … print(“no”) … Output: yes |
3) >>> z = 8 >>> if z <= 8: … print(“OK”) … Output: OK |
PROJECT
'''
Conditional Statements - Project
BOX OFFICE
__________________________________________________________
Your task is to write a program that sells tickets for a movie. Well,
maybe it just determines the price, but it's cool too.
The price depends on the user's age. The tickets are free for kids up to
the age of 3. For kids aged 4 - 10 you pay a reduced price of $6.
Seniors (at or over the age of 60) pay $8 for their ticket and all the others
have to pay the full regular price of $12.
And here's how you should write this program:
#1. Write code that will ask the user to enter their age. As we'll need
the age as a number and anything the user types from the keyboard is
a string, we'll have to convert user input to an integer.
To do that, use the int function and pass the input function to it
as an argument. If you don't know what it means, it's quite easy:
What we put in the parentheses of a function are arguments, so if we use
the print function like so:
print("hi"),
the string "hi" is an argument.
Or if we want to check the length of a string using the len function,
the string in the parentheses is an argument. We'll talk about it in
more detail when we discuss functions.
Anyway, you may put a function as an argument of another function.
So, if you want to print the length of the string "hi", you can do
it like so:
print(len("hi"))
What you need to do here is pass the input function as an argument
to the int function in order to convert the user input to a string.
And this value should be saved in a variable called age.
#2. Write conditional code (using if, elif and else) that will set the
ticket price according to the age of the user.
The price should be:
$12 - regular price
$8 - price for seniors (60 and above)
$6 - price for children (aged 4 - 10)
$0 - price for children under the age of 4
Don't print the price in the conditional code, just set it to the
appropriate value. Save it in the variable price.
For the seniors choose a comparison operator that will enable you
to use the number 60, so don't type age > 59.
Don't forget to indent your code!
#3. Write code that will tell the user the price to pay. It may look
like this:
As you are X years old, the ticket price is $Y.
Naturally, use appropriate variables instead of X and Y.
Use concatenation.
Remember also that you can only concatenate strings, not numbers, so
convert the numbers to strings first.
'''
PROJECT SOLUTION
##1.
age = int(input("Enter your age: "))
##2.
if age < 4:
price = 0
elif age < 11:
price = 6
elif age >= 60:
price = 8
else:
price = 12
##3.
print("As you are " + str(age)
+ " years old, the ticket price is $" + str(price) + ".")