Lab Condicionales 11
Lab Condicionales 11
Conditionals
Lab - Conditionals
Lab - If Statement
x = 5
if x < 10:
print("Less than 10")
Code Visualizer
If the boolean expression is false, the indented code is skipped, and the
program continues as normal.
x = 20
if x < 10:
print("Less than 10")
Code Visualizer
Lab - If Else Statement
x = 10
if x > 50:
print(str(x) + " is greater than 50")
else:
print(str(x) + " is less than 50")
Code Visualizer
The if part of the if else statement is written as before. The else keyword is
not indented; it should be aligned with the if keyword. else is followed by
a :. You do not use a boolean expression with else. All code that should run
when the boolean expression is false must be indented four spaces.
x = 50
if x > 50:
print(str(x) + " is greater than 50")
else:
print(str(x) + " is less than 50")
Code Visualizer
The output of the program does not make sense. 50 is not less than 50.
Sometimes using <= and >= need to be used. Be sure to think through all of
the possible outcomes, and make sure your code can function properly in
all of those scenarios.
Lab - Compound Conditional
x = 10
Code Visualizer
The code above will be true for any number that is greater than 5 and less
than 15. If x has the value of 5 or 15, then the boolean expression will be
false.
If you take the same code and change and to or, you get a very different
program.
x = 10
Code Visualizer
It does not matter what value you give to x, the boolean expression will
always be true. The boolean expression is true even if x is 5 or 15.
Compound Conditional Or
Lab - If Elif Else Statement
michelin_stars = 3
if michelin_stars == 1:
print("This is a very good restaurant")
elif michelin_stars == 2:
print("This is an excellent restaurant")
else:
print("This restaurant is among the best in the world")
Code Visualizer
The if elif else statements can also be faster than a series of if statements.
As soon as a boolean expression is true, Python stops computing the
remaining boolean expressions. Python will execute all of the if
statements, even if one of them is true.
Efficiency
Lab Challenge - Month of the Year
Conditionals Challenge
Write a program that determines the month of the year based on the value
of a variable called month. The variable will be a number from 1 to 12 ( 1 is
January, 2 is February, etc.). Use a print statement to write the month to
the screen.
Important, you will need to declare the variable month as you write and
test your code. However, do not submit your code to be graded with the
variable declaration. The auto-grader will declare the variable for you.
Code Visualizer