ย 
Search

Programming with Python Conditional statements


Python Conditional statements

Conditional statements refer to a statement which requires a particular condition to be met before executing a particular line or lines of code.


For example, we can write a program to check whether a user is allowed to go on a ride at a theme park. ๐ŸŽก๐ŸŽข


Let's say that the ride in question requires the user to at least 12 years of age. ๐Ÿ‘ฆ


Using the knowledge from the previous blogs, we can ask the user for their age and take this as input:


print ("Enter your age: ")
age = int(input())
#int() makes input an integer

NOTE: if you see a '#' at the start of a line, this is a 'comment', and is not run with the rest of the code.


Now, we have the user's age stored as an integer in the variable 'age'.


How can we check whether the user is at least 12?


We can do this using 'if statements'.


if age >= 12:
    print ("You can use the ride.")
else:
    print ("Sorry, you cannot use the ride.")

NOTE: >= is checking if it is equal to or greater than.

> is checking if it is greater than.

== is used to check if two things are equal.


This simply checks whether the user's age is at least 12. If it is, we let the user know they can use the ride.


If the user's input is not at least 12, we let them know they cannot use the ride.


We can have as many if statements, one after the other, as we would like to. If there is an upper age limit for using the ride then we can add an additional if statement checking this.


Think of some more examples where if statements can be used, and have a go at implementing these in Python!


Thanks โ˜บ๏ธ

1,307 views

Recent Posts

See All
ย