10. Wenn-dann-Anweisungen

Video link ../../_images/question_mark_1.svg

So far we’ve learned to create expressions, use variables, and make our own functions.

Our next step is to learn how to write code that will only run based on a certain condition. For example, we may want to draw „Game Over“ text on the screen–but only if the player has run out of lives.

To do this we need to learn how to use an if statement. The if statement is also known as a conditional statement. (You can use the term „conditional statement“ when you want to impress everyone how smart you are.) The if statement allows a computer to make a decision. Is it hot outside? Has the spaceship reached the edge of the screen? Has too much money been withdrawn from the account? A program can decide which block of code to run based on this statement.

10.1. Einfache Vergleiche

../../_images/scale.svg

Here are two example if statements. As you can probably guess, the statements see which variable is smaller, and which is larger.

Beispiel bedingte Anweisungen: kleiner, größer als
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# Variables used in the example ``if`` statements
a = 4
b = 5

# Basic comparisons
if a < b:
    print("a is less than b")

if a > b:
    print("a is greater than b")

print("Done")

Try running the code. You should get output that looks like this:

Ausgabe
a is less than b
Done

Since a is less than b, the first statement will print out if this code is run. Flip the values, and the second statement will run. If both variables a and b were equal to 4, then neither of the two statements would print because 4 is not greater than 4.

Play around with the program by adjusting the values to verify the code continues to do what we expect.

10.2. Flowcharts

To show the flow of a program a flowchart may be used. Most people can follow a flowchart even without an introduction to programming. See how the flowchart below matches with the code we just ran. if statements go in diamonds and have two possible paths out of them. Regular statements go in rectangles, and have only one exit path.

../../_images/flowchart_example.svg

Programmablaufplan

This book skips an in-depth look at flow-charting, but if you are curious and want to learn more, Wikipedia has a great article introducing how it works:

https://de.wikipedia.org/wiki/Programmablaufplan

10.3. More Comparison Types

The prior example checked to see if variables were „greater than“ or „less than.“ Numbers that were equal would not pass the test. To check if values are greater than or equal, we use the two characters >= right next to each other, with no space between. Let’s adjust our prior code sample:

Beispiel bedingte Anweisungen: kleiner oder gleich, größer oder gleich
1
2
3
4
5
if a <= b:
    print("a is less than or equal to b")

if a >= b:
    print("a is greater than or equal to b")

Die Zeichen <= und >= müssen in dieser Reihenfolge stehen und es darf kein Leerzeichen zwischen ihnen stehen. Zum Beispiel wird =< und auch < = nicht funktionieren.

When writing these statements out on actual paper, some new programmers like to use the symbol, because that’s what we learned in math. For example:

if a ≤ b:

This symbol doesn’t actually work in a program. Plus most people don’t know how to type it on the keyboard. (Just in case you are curious, to type it hold down the ‚alt‘ key while typing 243 on the number pad.) So when writing out code, particularly on paper, remember to use the two characters <= and not the one character symbol. If you encounter a written test or quiz, make sure to write it out correctly and not lose points.

The next set of code checks to see if two items are equal or not. If we want to check for equality, we use two equals signs in a row: ==. The operator for not equal is !=. Here they are in action. Add them to the bottom of the other code we were working on, and try them out.

Example if statements: „equal“ and „not equal“
1
2
3
4
5
6
7
# Equal
if a == b:
    print("a is equal to b")

# Not equal
if a != b:
    print("a and b are not equal")

Achtung

Lerne wann = und wann == verwendet werden müssen.

It is very easy to mix up when to use == and =. Use == if you are asking if they are equal, use = if you are assigning a value.

Die beiden häufigsten Fehler beim Vertauschen der Operatoren = und ==, werden unten gezeigt:

1
2
3
4
5
6
# This is wrong
a == 1

# This is also wrong
if a = 1:
    print("A is one")

Halt! Nimm dir noch etwas Zeit, gehe zurück und sieh dir sorgfältig die letzten beiden Programmbeispiele an. Spare später Zeit dadurch, dass du sicher verstehst, wann du = und wann == verwenden musst. Rate nicht einfach.

10.4. Einrückung

Indentation matters. Each line under the if statement that is indented will only be executed if the statement is True. In this example, the three lines indented under the if statement will run only if true, the fourth print statement will always run because it is not indented under an if statement.

1
2
3
4
5
6
if a == 1:
    print("If a is one, this will print.")
    print("So will this.")
    print("And this.")

print("This will always print because it is not indented.")

The indentation amount must be the same. This wandering code doesn’t work.

1
2
3
4
if a == 1:
  print("Indented two spaces.")
    print("Indented four. This will generate an error.")
   print("The computer will want you to make up your mind.")

Once an if statement has been finished, it is not possible to re-indent to go back to it. The test has to be performed again. So this code example doesn’t work at all:

1
2
3
4
5
6
if a == 1:
    print("If a is one, this will print.")
    print("So will this.")

print("This will always print because it is not indented.")
    print("This will generate an error. Why it is indented?")

If you try running it, you’ll get the following IndentationError:

  File "c:/my_code/test.py", line 8
    print("This will generate an error. Why it is indented?")
    ^
IndentationError: unexpected indent

10.5. Verwendung von und/oder

An if statement can check multiple conditions by chaining together comparisons with and and or. These are also considered to be operators just like the + and - characters are. Go ahead and create a third variable c and try using these two new operators yourself.

Beispiel bedingte Anweisungen: Verwendung von and und or
1
2
3
4
5
6
7
# And
if a < b and a < c:
    print("a is less than b and c")

# Non-exclusive or
if a < b or a < c:
    print("a is less than either b or c (or both)")

Hinweis

Wiederhole bitte selbst.

A common mistake is to omit a variable when checking it against multiple conditions. You cannot write if a < b or c. Neither will if a < b or < c work. The computer does not know what to check against the variable c. It will not assume to check it against a. You need the full if a < b or a < c for it to work correctly.

1
2
3
# This is not correct
if a < b or < c:
    print("a is less than b and c")

10.6. Boolesche Variablen

Python supports Boolean variables. What are Boolean variables? Boolean variables can store a value of either True or False. Boolean algebra was developed by George Boole back in 1854, well before electronic computers. Yet his work forms the basis of how computer logic works. If only he knew how important his work would become!

Eine bedingte Anweisung benötigt einen Ausdruck, der zu True oder False ausgewertet wird. Was etwas merkwürdig erscheinen kann, ist, dass wir keine Vergleiche anstellen müssen, wenn die Variable schon zu True oder False ausgewertet wird.

For example, in this code we set the variable a to True. Our if statement does’t need a comparison. If a is True it will execute the statement, if it is False it will not.

Bedingte Anweisungen und Boolesche Datentypen
1
2
3
4
# Boolean data type. This is legal!
a = True
if a:
    print("a is true")

Another operator we can use is the not operator. You can take any statement or boolean and flip between True/False. The statement if a runs if a is True, the statement if not a runs if the statement is False.

Der not-Operator - Beispiel 2
1
2
3
# How to use the not function
if not a:
    print("a is false")

It is also possible to use Boolean variables with the and and or operators.

and mit Booleschen Variablen verwenden
1
2
3
4
5
a = True
b = False

if a and b:
    print("a and b are both true")

Achtung

Wer hätte gedacht, dass wahr/falsch so schwierig sein kann?

Es ist ebenfalls möglich das Ergebnis eines Vergleichs an eine Variable zuzuweisen. Im Code unten werden die Variablen a und b verglichen. Wenn sie gleich sind, wird c True andernfalls False zugewiesen.

Werte an Boolesche Datentypen zuweisen
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
a = 3
b = 3

# This next line is strange-looking, but legal.
# c will be true or false, depending if
# a and b are equal.
c = a == b

# Prints value of c, in this case True
print(c)

Hinweis

Null bedeutet False. Alles andere ist True.

It is possible to create an if statement with a condition that does not evaluate to True or False. Because this is confusing, we don’t use this fact a lot, but it is important to understand how the computer handles these values when searching for problems. These two examples will run, and will cause the text to be printed out because the values in the if statement are non-zero:

1
2
3
4
if 1:
    print("1")
if "A":
    print("A")

The code below will not print out anything because the value in the if statement is zero. The value zero is treated as False. Any value other than zero (like 2, -1, 600, or even „Fred“) is considered True.

1
2
if 0:
    print("Zero")

10.7. Die input-Funktion

Statt die Werte fest in unser Programm zu schreiben, können wir die input-Funktion verwenden, um den Benutzer aufzuforderen etwas einzugeben. Die input-Funktion ist einigermaßen einfach zu verwenden:

1
2
temperature = input("What is the temperature in Fahrenheit? ")
print("You said the temperature was " + temperature + ".")
../../_images/keyboard.svg

Gib als Argument beim Aufruf von input einfach den Text der Eingabeaufforderung an. Was immer der Benutzer eingibt, wird in der Variablen auf der linken Seite der Zuweisung gespeichert.

Beachte, dass ein Fragezeichen und ein Leerzeichen am Ende der Zeichenkette steht. Wenn du das weg lässt, wird der Text, den der Benutzer eingibt, direkt an die Eingabeaufforderung angehängt. Das sieht aber schrecklich aus. Der Benutzer wird verführt, ein Leerzeichen als Erstes einzugeben. Das wird uns aber die Sache später erschweren.

Es gibt noch etwas zu lernen. Wir können die Eingabe des Benutzers nicht direkt mit einer Zahl vergleichen. Dieses Programm:

1
2
3
temperature = input("What is the temperature in Fahrenheit? ")
if temperature > 90:
    print("It is hot outside.")

…will fail with a TypeError:

TypeError: '>' not supported between instances of 'str' and 'int'

Was immer der Benutzer eingibt wird als Text gespeichert. Wir nennen einen Text auch Zeichenkette, weil es für den Rechner nur eine Kette von Zeichen ist. Eine Zeichenkette (englisch string) ist etwas anderes als eine Zahl und der Rechner weiß nicht, wie er sie vergleichen soll.

Therefore, we need to convert the input into a number. We can do with with the int for integers. If we have floating point numbers, use the float function.

In this example we get the input, convert it to an integer, and then we can use it in an if statement.

1
2
3
4
5
6
7
8
9
# Get input from the user
temperature = input("What is the temperature in Fahrenheit? ")

# Convert the input to an integer
temperature = int(temperature)

# Do our comparison
if temperature > 90:
    print("It is hot outside.")

You can chain the input and int functions on one line if you like, as shown here:

1
2
3
4
5
6
# Get input from the user
temperature = int(input("What is the temperature in Fahrenheit? "))

# Do our comparison
if temperature > 90:
    print("It is hot outside.")

10.8. Andernfalls und andernfalls wenn

So far, we’ve used simple if statements to run a block of code, or not run it. What if we want to select between two blocks of code? What if we want to run one of four different blocks? To do this, we need „else“ and „else if“ logic.

Let’s start with a simple if statement that prints if it is hot outside:

1
2
3
4
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
print("Done")

If the programmer wants code to be executed if it is not hot, she can use the else statement. As for indentation, notice how the else is lined up with the i in the if statement. Also notice how else is followed by a colon just like the if statement. Try running this code. The if statement will always run one of the two blocks, but never both.

Beispiel zweiseitige Auswahl
1
2
3
4
5
6
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
else:
    print("It is not hot outside")
print("Done")

In the case of an if…else statement, one block of code will always be executed. The first block will be executed if the statement evaluates to True, the second block if it evaluates to False.

It is possible to chain several if statements together using the else…if statement. Python abbreviates this as elif. In this example we add a third possible combination using elif.

Beispiel verschachtelte Auswahl
1
2
3
4
5
6
7
8
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
elif temperature < 30:
    print("It is cold outside")
else:
    print("It is not hot outside")
print("Done")

In this next example, we’ve made a mistake. The program will output „It is hot outside“ even if the user types in 120 degrees. Why? How can the code be fixed?

Beispiel verschachtelte Auswahl mit falscher Anordnung
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
elif temperature > 110:
    print("Oh man, you could fry eggs on the pavement!")
elif temperature < 30:
    print("It is cold outside")
else:
    print("It is ok outside")
print("Done")

The computer doesn’t do a „best-fit“, it looks at the if statement in order. As 120 is greater than 90, it will run the first condition and skip the rest. To fix this code, we need to reorder it.

Beispiel verschachtelte Auswahl mit falscher Anordnung
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 110:
    print("Oh man, you could fry eggs on the pavement!")
elif temperature > 90:
    print("It is hot outside")
elif temperature < 30:
    print("It is cold outside")
else:
    print("It is ok outside")
print("Done")

10.9. Textvergleiche

It is possible to use an if statement to check text, as shown in this example.

Groß-/Kleinschreibungsabhängiger Textvergleich
1
2
3
4
5
user_name = input("What is your name? ")
if user_name == "Paul":
    print("You have a nice name.")
else:
    print("Your name is ok.")

The prior example will only match if the user enters „Paul“ with a capital P. It will not work if the user enters lower-case „paul“ or upper-case „PAUL“.

Ein üblicher Fehler ist, die Anführungszeichen um die Zeichenkette, mit der verglichen werden soll, zu vergessen. Im Beispiel unten wird der Rechner annehmen, dass Paul eine Variable ist, die einen Wert speichert. Er wird einen Fehler anzeigen, weil er keine Ahnung hat, was in der Variablen Paul gespeichert ist.

Fehlerhafter Vergleich
1
2
3
4
5
user_name = input("What is your name? ")
if user_name == Paul: # This does not work because quotes are missing
    print("You have a nice name.")
else:
    print("Your name is ok.")

10.9.1. Mehrfache Textvergleiche

When comparing a variable to multiple possible strings of text, it is important to remember that the comparison must include the variable. For example:

# This does not work! It will always be true
if user_name == "Paul" or "Mary":

Instead, the code should read like this:

# This does work
if user_name == "Paul" or user_name == "Mary":

Confusingly, the first example will run, but it will always trigger the if statement even if the name isn’t Paul or Mary. This is because for any value other than zero, the computer assumes to mean True. „Mary“ isn’t zero. So to the computer „Mary“ is the same thing as True and so it will run the code in the if statement.

10.9.2. Case-Insensitive Comparisons

If the program needs to match text, and we don’t care if it is upper or lower case, we need a case-insensitive comparison. The easiest way to do that is to convert everything to lower-case, then compare. This can be done with the lower() command.

Achtung

Lerne unabhängig zu sein.

The example below will take whatever the user enters, convert it to lower-case, and then do the comparison. Important: Don’t convert to lower-case and compare it against a string that has uppercase! Then you’ll never match.

Groß-/Kleinschreibungsunabhängige Textvergleiche
1
2
3
4
5
user_name = input("What is your name? ")
if user_name.lower() == "paul":
    print("You have a nice name.")
else:
    print("Your name is ok.")

10.10. Review

With the introduction of if statements we’ve learned how to run code only if a condition is true. By adding in elif and else statements we can run one of multiple possible code blocks depending upon a condition.

We’ve learned that we write conditions using comparison operators like < and >. We’ve learned that == is the comparison operator for asking if two items are equal, while = is the assignment operator used to set a variable’s value. We can reverse logic using the not operator.

Finally, we were introduced to Boolean values, where variables can store True or False. The if statements can operate based on those values.

10.10.1. Beispiel bedingte Anweisungen

The next set of example code below runs through all the concepts talked about earlier.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://programarcadegames.com/
# http://simpson.edu/computer-science/

# Explanation video: http://youtu.be/pDpNSck2aXQ

# Variables used in the example if statements
a = 4
b = 5
c = 6

# Basic comparisons
if a < b:
    print("a is less than b")

if a > b:
    print("a is greater than than b")

if a <= b:
    print("a is less than or equal to b")

if a >= b:
    print("a is greater than or equal to b")

# NOTE: It is very easy to mix when to use == and =.
# Use == if you are asking if they are equal, use =
# if you are assigning a value.
if a == b:
    print("a is equal to b")

# Not equal
if a != b:
    print("a and b are not equal")

# And
if a < b and a < c:
    print("a is less than b and c")

# Non-exclusive or
if a < b or a < c:
    print("a is less than either a or b (or both)")


# Boolean data type. This is legal!
a = True
if a:
    print("a is true")

if not a:
    print("a is false")

a = True
b = False

if a and b:
    print("a and b are both true")

a = 3
b = 3
c = a == b
print(c)

# These are also legal and will trigger as being true because
# the values are not zero:
if 1:
    print("1")
if "A":
    print("A")

# This will not trigger as true because it is zero.
if 0:
    print("Zero")

# Comparing variables to multiple values.
# The first if statement appears to work, but it will always
# trigger as true even if the variable a is not equal to b.
# This is because "b" by itself is considered true.
a = "c"
if a == "B" or "b":
    print("a is equal to b. Maybe.")

# This is the proper way to do the if statement.
if a == "B" or a == "b":
    print("a is equal to b.")

# Example 1: If statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
print("Done")

# Example 2: Else statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
else:
    print("It is not hot outside")
print("Done")

# Example 3: Else if statement
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
elif temperature < 30:
    print("It is cold outside")
else:
    print("It is not hot outside")
print("Done")

# Example 4: Ordering of statements
# Something with this is wrong. What?
temperature = int(input("What is the temperature in Fahrenheit? "))
if temperature > 90:
    print("It is hot outside")
elif temperature > 110:
    print("Oh man, you could fry eggs on the pavement!")
elif temperature < 30:
    print("It is cold outside")
else:
    print("It is ok outside")
print("Done")

# Comparisons using string/text
# The input statement will ask the user for input and put it in user_name.
user_name = input("What is your name? ")
if user_name == "Paul":
    print("You have a nice name.")
else:
    print("Your name is ok.")