Conditionals in Python
Similar to for-loops in Python, conditionals provide a mechanism to control the flow of execution of a program in many programming languages. In Python, the
if-statement will run a section of code if and only if the conditional provided is true.
Many people consider 7 to be a lucky number. The Python code below uses an
if statement to print out a message if Python randomly choose a lucky number:
num = random.randint(1, 10)
if num == 7:
print("Your Lucky Day!")
There are a few features to notice:
- The line of code begins with an
if, then followed by a conditional, and ends with a colon (
- The block of code following the
forstatement is indented. This indentation defines the block of code that will run ONLY if the conditional is true.
- The code after the if-statement, back at the original indentation, will only run after the for-loop finishes running.
Notice the two different outputs of the same code based on the randomly generated value:
Today is Your Lucky Day! Number: 7
In Python, the conditional component of an if-statement is nearly identical to the conditionals you have used with Pandas except that you are no longer working within the context of a DataFrame.
- You will use
ifstatements to compare the values of individual variables in Python (ex: values as part of a simulation) instead of values in a DataFrame.
- You can still use the six logical operators,
- You can still combined multiple conditionals, except you must use
Often you may want to run different code when a conditional is true and false. To run code when the conditional is false, an
else statement is used. Since
else is a control flow statement, it needs a colon (
:) at the end and nothing else!
Your coin flipped heads!
Your coin flipped tails!
if-statements: Conditional Data on Simulation
One of the most useful applications of conditionals is to add conditional data to your DataFrame. For example, roulette is a classic casino game that involves a wheel with 38 equal-sized wedges: 18 red wedges, 18 black wedges, and 2 green wedges.
A simulation of your profit playing roulette while betting on red can be done by a conditional that checks if you the result of the game was red:
- If the result was red, you gain $1. (You get your $1 bet back and gain $1 from the casino.)
- If the result was NOT red, you lose $1. (You lose your $1 bet.)
Running this as a simulation:
Example Walk-Throughs with Worksheets
Video 1: Examples of Conditionals in Python
Practice QuestionsQ1: In which case would "Here" print in the following if-statement?
Q2: Which of the following is not part of the correct syntax for an if-statement?
Q3: What would the value of n be after running the follwing code chunk?
Q4: What would print after running the follwing code chunk?
Q5: What would print after running the following code chunk?
Q6: In a normal distribution, which two statistics are both equal to zero?