Sign InCoursewareNuggetsTutorials CoursesCodePad

If Statements

Tali plans to explore Min Mountain tomorrow to look for the magic box. "If it rains tomorrow, bring a raincoat," Andrew reminds her. "If it's sunny, don't forget the sunscreen." Rain or shine is an example of a conditional question. Tali will need to make her decision based on the answer to this question. We call these sorts of questions conditions.

In our daily lives, conditional cases are everywhere:

If it is Tuesday, wear tennis shoes to PE. 
If you have a fast pass, go to the left lane. Otherwise, go to the right lane.
If you're taller than 52 inches, you ride roller coasters 1, 2, and 3. Else if taller than 48 inches, ride roller coasters 1 and 2. Else if taller than 42 inches, ride roller coaster 1.

The list can go on and on. In programming, we can also ask conditional questions and make decisions based on the answers. To do so, we use if statements.

if ❮condition❯: 
    ❮then statements❯

If the condition is true, the program will execute the then statements. If the condition is not true, it will jump to the next statement after the if statement. Let's look at how the rain or shine example would be written in Python:

weather = input("Please enter the weather today (rain or shine):") if weather == "rain": # if condition: true if weather is equal to "rain" print("Please bring a raincoat!") # then statement: only executed when condition is true if weather == "shine": print("Please bring sunscreen!")

In Python, an if statement is made by the if keyword, followed by a condition, and then a colon(:). After this if statement, we can write a block of statements, or just a single statement, which will be run only if the if statement's condition is true. Statements are grouped into blocks based on their indentations -- that's the amount of white space at the beginning of the line. Therefore, the white space at the beginning of each line is important here. When the indentation changes, a new block is created.


Python Indentation Tip
TipConsistent spacing is important in Python. Use the same amount of spaces as indentation in all blocks throughout your program.
© CS Wonders·About·Gallery·Fun Facts·Cheatsheet