In Python, branching control structures are used to change the normal flow of execution based on some condition. There are three types of branching control structures in Python:
If statements are an example of a branching control structure. They allow your code to respond to things like variable values and user input by executing different blocks of code in different situations.
The following is an example of an if statement:
if x == 10: print("x is equal to 10")
In this example, the value of the variable x is checked to see if it is equal to 10. If it is, the block of code inside the if statement will be executed. Otherwise, the block of code will be skipped. See the diagram below for a visual representation of this:
I'd like you to notice a few other things about these lines of code, as well:
Here is an example of what it would look like to put this if statement and a code block in a regular program:
print("This is a regular line of code") if x == 10: print("x is equal to 10") print("This line also only gets printed if x is equal to 10") print("This will be printed no matter what.")
So, if x is equal to 10 above, you will see the following when you run the program:
This is a regular line of code x is equal to 10 This line also only gets printed if x is equal to 10 This will be printed no matter what.
If x is equal to anything else, then you would see the following:
This is a regular line of code This will be printed no matter what.
The following is an example of an else statement:
if x == 10: print("x is equal to 10") else: print("x is not equal to 10")
In this example, the value of the variable x is checked to see if it is equal to 10. If it is, the block of code inside the if statement will be executed. Otherwise, the block of code inside the else statement will be executed.
Here is a diagram that shows how this works:
Notice that in the code, the “if” line and the “else” line are both indented the same. Also, the blocks of code beneath these lines are all indented one level more than the if and else lines. This is how Python. knows that these statements and blocks of code go together.
A simple way to think about an if…else block is an “either/or” situation, where you are telling Python to “do thing A” if something is true, and to “do thing B” if it isn't.
The following is an example of an elif statement:
if x == 10: print("x is equal to 10") elif x == 20: print("x is equal to 20") else: print("x is not equal to 10 or 20")
In this example, the value of the variable x is checked to see if it is equal to 10. If it is, the block of code inside the if statement will be executed. Otherwise, the value of x is checked to see if it is equal to 20. If it is, the block of code inside the elif statement will be executed. Otherwise, the block of code inside the else statement will be executed.
Notice that in the code block above, there are 3 different possible outcomes:
Here is a visual flowchart showing how this block of code works:
Also, notice that the if and the elif lines have expressions, but the else line doesn't. This is because the else block is what gets executed if none of the expressions in if and elif are true.
While you are always required to start out with an if, elif and else are optional. You can also have as many elifs as you want, with or without an else. So many possibilities!
Branching control structures (if..elif…else) are an essential part of Python programming, and pretty much every other kind of programming as well. By understanding how branching control structures work, you can write more powerful and efficient code.
Here are some additional tips for using branching control structures:
With a little practice, you'll be using branching control structures like a pro!
Player 1 and Player 2 are playing Rock, Paper, Scissors. If Player 1 chooses Rock, then what happens if Player 2 chooses Rock, Paper or Scissors?
Can you write an if…elif…else block in the window below that will show the correct responses based on what Player 2 chooses?
No terms have been published for this module.
Test your knowledge of this module by choosing options below. You can keep trying until you get the right answer.
Skip to the Next QuestionLet's make a simple game - The computer will come up with a secret number, and the user will try to guess what it is. This will require us to use an "if" and "else" statement to decide whether or not the user guessed correctly. I'll provide a lot of the code, and challenge you to fill in the most important part: The part that decides whether the user has guessed right or wrong.
Remember, there are two different operators that look very similar:
The = operator, called the "assignment" operator, actually assigns a value to a variable, much like putting something in a container. For example, if we code the following:
x = 5
We are telling Python that the variable x is now equal to 5. To put it another way, it's like putting the number 5 in a container labeled "x". The variable x will stay equal to 5 until we change it to something else.
An operator that might feel very similar to this is the "comparison" operator, which is written using two "equals" signs, like this: ==
Where the assignment operator tells a variable it is equal to something, the comparison operator asks, "are these two things equal?". The result of a comparison is always either "True" or "False".
Here are a few examples in code:
2+1 == 3
# This is True, because "2+1" is equal to "3"
"three" == 3
# This is False, because even though they are conceptually similar,
# Python doesn't understand anything other than the fact
# that a string can't equal an int.
x * 6 == x * 3 * 2
# This will be True, no matter the value of x,
# because one side will always be equal to the other side.
"Bill" == "bill"
# Even though they are the same letters on each side, this is False because Python
# sees uppercase and lowercase letters as different.
So now that we have an idea of how the comparison operators work, let's look again at the way an if statement would use those. An if statement does something if the expression part of the statement is equal to True. Look at the following:
x = 5
if (x == 5):
print("X is equal to 5")
Since x is indeed equal to 5, Python will execute (or run) the code that is directly indented below the if statement. When you run this code, Python will print "X is equal to 5". Try it out - I'll wait here. You can do this in PyCharm or in online-python.com -- Either will work.(NOTE: indent the line starting with "print" by one tab)
Now, try changing the x = 5 line to the following:
x = 10
Notice that when you run the code, nothing happens. Well, nothing you can see, anyway. What happens is that Python sets x to equal 10. Then, Python asks whether x is equal to 5. Since that is False, then Python just skips the indented code block, and the program ends without printing anything.
What if we wanted to print something if the if statement is true, but print something different if it was false? We can do that! The solution is to add an "else" statement, like this:
x = 10
if (x == 5):
print("X is equal to 5")
else:
print("X is NOT equal to 5")
In the case above, Python will print "X is NOT equal to 5", because x is 10 and the if statement is False.
So, now for the challenge…
Use what you've learned about if and else to finish the following code. In it, the computer will generate a random number, and the user will have a chance to enter a guess as to what the number might be. Your job is to tell the user whether their number is the same as the computer's secret number or not.
Here is your starter code:
import random
# the above line tells Python that we want to
# import and use the random module.
intSecretNumber = random.randint(1,10)
# The line above uses the random module's randint (random integer)
# function to generate a random int between 1 and 10.
# The random number is assigned to the variable "intSecretNumber"
intUserGuess = int(input("Guess a number between 1 and 10: "))
# this line of code asks the user to input a number between 1 and 10,
# converts their input string to an int,
# and then assigns it to "intUSerGuess".
For a BONUS CHALLENGE, if the user guesses wrong you can tell them what the secret number was after they miss.
Use if statements to create a calculator that will preform more than one calculation based on user input. First, it should ask the user what calculation they want to perform (for example, farenheit to celsius vs. celsius to farenheit), and then it should prompt them for the input, and finally, produce the correct calculation based on those factors. Pay attention in this program to the user experience. Think of how you can make the user experience easier, as well as more visually pleasant.
Here is some template code to get you started:
# Show the UI print("#" * 80) print("#" * 9, " " * 60, "#"*9) print("#" * 9, "Advanced Calculator".center(60), "#" * 9) print("#" * 9, " " * 60, "#"*9) print("#" * 80) # Welcome the user # Show the menu options # Get input from the user. # if the user chooses 1, do C to F # ask for degrees in C # do the calculation # if the user chooses 2, do F to C # if the user enters anything else, give an error message
Please submit the complete program as a .py file.