Discover Python and Patterns (3): Branching

Published November 24, 2019
Advertisement

Programs in the previous post always lead to the same result. Here, I show you the basics of branching, or how to change the flow of a program depending on cases.

If statement

If we want to display a message when the player types a specific word, we can use the following syntax:

word = input("Enter the magic word: ")
if word == "please":
    print("This is correct, you win!")
print("Thank you for playing this game!")

If you run this program, and type “please”, then you see the message “This is correct, you win!” as well as the final message. If you don’t, you only see the final message, “Thank you for playing this game!”.

In this example, we use the if statement:

if <condition>:
    <what to do if the condition is met>
<these lines are always executed>

The <condition> is an expression that, if evaluated as True, leads to the execution of the following block. If it evaluated as False, then the following block is skipped.

In the example, the condition is word == "please" and we can translate it into: is it true that word equals “please”? Please note the double equal symbol “==”: this is not the single equal symbol, which is the assignment. If you type word = "please", it means word takes the value “please”, and it is evaluated as True (because “please” is not None). Throughout the series, I’ll show you many cases of condition expressions.

Blocks and indentation

To understand what the if statement executes, you need to understand blocks in Python. In this language, indentation defines blocks: all lines with the same combination of space symbols before the expression are in the same block.

In the example, we have a single line print("This is correct, you win!") with an indentation of four spaces. If we want to add a second line to this block, we must also start it with four spaces:

word = input("Enter the magic word: ")
if word == "please":
    print("This is correct.")
    print("You win!")
print("Thank you for playing this game!")

The second line can’t begin with 3 or 5 spaces or a tab symbol with a width of 4 spaces. It must begin with the same combination of space symbol as the first line of the block. If we want to use, for instance, an indentation of 3 spaces, all lines of the block must begin with exactly 3 spaces. You can choose a different combination for each block.

Negation

In the previous example...

Continue reading on https://learngameprog.com...


0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement