7. Variablen und Ausdrücke

Video link ../../_images/drawing.png

We’ve learned how to import a library and call functions. The next step is to make our code more flexible. What if we could take that drawing code and put it into our own functions? Then we could write custom functions to draw trees, houses, even rainbows. Our code could look like this:

draw_tree(225, 35)
draw_tree(420, 45)
draw_house(720, 60)
draw_snow_person(300, 20)

Creating flexible functions isn’t just for drawing. Functions are the basic building block of almost every type of programming. If you are running a program, it is just functions, built on top of functions, built on yet more functions.

To be able to create our own functions, we need to cover three things.

  • Wie man Variablen verwendet (dieses Kapitel)

  • Wie man Ausdrücke eingibt (dieses Kapitel)

  • How to create our own functions (the next two chapters)

7.1. Wie man Variablen verwendet

../../_images/expression.jpg

A variable is a value the computer stores in memory that can change. That is, it varies. Here is a quick example:

# What will this print?
x = 5
print(x)

Was wird der Programmcode oben ausgeben? Er wird 5 ausgeben.

x is a variable. The = is called an assignment operator. It assigns the value on the right side to the variable on the left.

Hier ist ein anderes Beispiel. Es ist sehr ähnlich, aber etwas ist unterschiedlich. Was wird es ausgeben?

# What will this print?
x = 5
print("x")

Der Code oben gibt x aus. Warum nicht 5? Der Grund ist:

  • Wenn es keine Anführungszeichen gibt, wertet der Rechner den Code genauso wie einen mathematischen Ausdruck aus.

  • Wenn es Anführungszeichen gibt, behandeln wir alles zwischen den Anführungszeichen als Zeichenkette und verändern sie nicht.

Das ist, was wir tatsächlich die Zeichen zwischen den Anführungszeichen nennen. Einen String, was kurz für „string of characters“ (Kette von Zeichen) steht. Wir nennen es nicht „Text“.

Der folgende Code gibt gar nichts aus:

print(Have a great day!)

The code above will fail because the computer will think that it should evaluate Have a great day! as a mathematical expression. It isn’t, so the computer gets confused and generates a syntax error. That’s why we need quotes:

print("Have a great day!")

7.1.1. Variablen und Funktionsnamen

../../_images/hello.svg

Variablennamen und Funktionsnamen folgen den gleichen Regeln. Es gibt Namen, die du verwenden solltest, Namen, die du nicht verwenden solltest, und Namen, die du nicht verwenden kannst.

Variable names should be descriptive, all lower case, and if you have multiple words, separate the words by an underscore. Variable names can’t start with a number nor have a space or any symbol other than an underscore. Here are some examples:

Good variables:
  • temperature_in_celsius

  • tree_position_1

  • tree_position_2

  • car_speed

  • number_of_children

  • simpson

Bad variable names that still work:
  • temperatueInCelsius - verwendet Großbuchstaben. Bleibe bei Kleinbuchstaben und verwende Unterstriche.

  • x - zu kurz und nicht beschreibend

  • Smith - Starts with a capital letter.

Variablen die nicht erlaubt sind:
  • tree position - Leerzeichen kann man nicht verwenden

  • 4runner - darf nicht mit einer Ziffer anfangen

Manchmal möchten wir Variablen erzeugen, die sich nicht verändern. Wir nennen diese Variablen Konstanten. Nach Konvention werden diese Variablennamen in Blockbuchstaben geschrieben. Sie sind nur Variablen die Blockbuchstaben verwenden. Zum Beispiel:

PI = 3.14159
SCREEN_WIDTH = 600
RED = (255, 0 ,0)

Good variable names help make code readable.

For example, what does this code do? It is hard to tell.

m = 294 / 10.5
print(m)

Here we use variables to separate the formula from the numbers. A bit easier to change the values, and a bit easier to figure out the formula.

m = 294
g = 10.5
m2 = m / g
print(m2)

Instead of using short variable names, if we use use descriptive variable names and comments the code is very easy to understand.

# Calculate mpg using good variable names
miles_driven = 294
gallons_used = 10.5
mpg = miles_driven / gallons_used
print(mpg)

Good variable names make code readable. Even a non-programmer could scan that code and understand what it does. Straightforward code requires less effort to find problems. Therefore, take the time to name your variables well.

7.2. Wie man Ausdrücke erstellt

Great! We are part-way there. To manipulate data with a computer, we use expressions. An expression is simply a mathematical equation.

7.2.1. Verwendung von Operatoren in Ausdrücken

../../_images/calculator.svg

Expressions use operators. That’s just a fancy word for symbols like addition (+) and subtraction(-). Here’s an example:

# What will this print?
x = 5 + 10
print(x)

Wie du wahrscheinlich ahnst, wird dies 15 ausgeben. Wir nennen das +-Zeichen einen Operator. Hier sind ein paar andere Operatoren:

Operator

Beschreibung

+

Addition

-

Subtraktion

*

Multiplikation

**

Exponentiation (hoch)

/

Division

//

Ganzzahl-Division (rundet ab)

%

Modulo (ergibt den Rest einer Division)

There are two things that don’t work like mathematics. First, there is no „juxtaposition“ used to multiply items. Second, the = is not an algebraic equality.

7.2.2. Auslassen des Multiplikationszeichens funktioniert nicht

Die Auslassung des Multiplikationszeichens funktioniert nicht. Das folgende Beispiel wird nicht funktionieren:

# The last two lines will error
x = 3
y = 2x
z = 2(3 + x)

Du kannst den Code oben durch explizites Multiplizieren zum Laufen bringen:

# This code works. Although it doesn't print anything.
x = 3
y = 2 * x
z = 2 * (3 + x)

Einfach genug. Denke nur daran, jedes mal * zu verwenden, wenn du multiplizieren willst.

7.2.3. Zuweisungsoperatoren

The = doesn’t work the same as in algebra. The = takes the expression to the right and evaluates it. The resulting value is stored into a variable on the left of the =. For example this stores a 7 into the variable x:

x = 3 + 4

In algebra, this next line of code would be ok. It does not work in Python however, because the only thing that can be on the left is a variable:

3 + 4 = x

Variables can be used in the expression. This example works fine, and stores 17 into z:

x = 5
y = 6
z = x + 2 * y

This next set of code doesn’t work. On the left of the = in that last line, there’s an expression. We need just a single variable for it to work. How would you re-write it to work?

# Last line has more than a variable on the left, doesn't
# work.
x = 5
y = 6
2 * z = x + y

The fact that the = sign isn’t an algebraic equality allows us to do some strange expressions that don’t make sense in algebra. Look at the this set of code and the comments that explain it:

# This works, and prints "3"
x = 3
print(x)

# This works too, even if it is invalid in algebra.
# It takes the value of x (which is 3) and adds one. Then stores
# the result (4) back in x. So we'll print "4".
x = x + 1
print(x)

7.2.4. Increasing a Variable

../../_images/increase.svg

What if we want to change a value stored in a variable? We need to use an assignment operator.

For example, take a look at this code. It prints the number 4 twice. First, we assign 3 to x. Then, every time we print we add one to x. We aren’t changing the original value of x, so we don’t print 4 and then 5. The variable x only holds the number 3.

# Add one to x, but the number x holds does not change.
x = 3
print(x + 1)
print(x + 1)

Take a look at this example. This example prints 3. It does add 1 to x. But it does nothing with the result. We don’t print it. Just like the prior example, the number in x doesn’t change.

# Add one to x, but the number x holds still does not change.
x = 3
x + 1
print(x)

Now look at this example. We use the assignment operator. We store into x the result of x + 1. This does increase the value stored in x and therefore we print out a 4.

x = 3
x = x + 1
print(x)

Bemerkung

It can be confusing to learn when to use x + 1 and when to use x = x + 1. Remember, the former does not change the value of x.

7.2.5. Increment/Decrement Operators

../../_images/up_down.svg

The = symbol isn’t the only assignment operator. Here are the other assignment operators:

Operator

Beschreibung

=

Zuweisung

+=

Inkrement

-=

Dekrement

*=

Multiply

/=

Divide

Because statements like x = x + 1 are so common, we can shorten this using the += assignment operator. Examine this code to see how it works:

# This works, and prints "3"
x = 3
print(x)

# Make x bigger by one using the regular
# assignment operator.
x = x + 1
print(x)

# Make x bigger by one, using the +=
# assignment operator.
x += 1
print(x)

# Make x smaller by five using the -=
# operator.
x -= 5
print(x)

Remember, if you want to increase or decrease a variable, you need to use an assignment operator.

Oh, and a common mistake is to mix the + and += operator as shown in this example. It doesn’t just add one to x, it doubles x and adds one.

# This doubles x, and then adds one.
# Probably not what the programmer intended.
x += x + 1

7.2.6. Verwendung von Funktionsaufrufen in Ausdrücken

Expressions are not limited to assignment statements. We can use expressions as parameters in function calls. This can be useful when you need a quick calculation. For example, what if we want to draw a circle in the center of the screen?

By creating variables for the height and width of the screen, we can set the screen size, and also do a quick calculation to find the screen center. In this example we use constant variables for the screen width and height. Then use some math to calculate the center of the screen.

Calculating the center of the screen
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import arcade

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

arcade.open_window(SCREEN_WIDTH, SCREEN_HEIGHT, "Drawing Example")

arcade.set_background_color(arcade.color.WHITE)

arcade.start_render()

# Instead of this:
# arcade.draw_circle_filled(400, 300, 50, arcade.color.FOREST_GREEN)
# do this:
arcade.draw_circle_filled(SCREEN_WIDTH / 2,
                          SCREEN_HEIGHT / 2,
                          50,
                          arcade.color.FOREST_GREEN)

arcade.finish_render()
arcade.run()

The great thing about this is that the variables which control the screen size can be changed, and the circle will automatically be re-centered. Had we simply coded (400, 300) as the center, we’d need to go and change that number as well. Perhaps not a big deal with a small program, but as our programs get larger it saves a lot of time.

7.2.7. Rangfolge der Operatoren

../../_images/calculator_2.svg

Python will evaluate expressions using the same order of operations you learned in math. For example this expression does not correctly calculate the average:

average = 90 + 86 + 71 + 100 + 98 / 5

The first operation to be calculated is 98 / 5, rather than adding up the numbers. That is, the computer calculates this equation instead:

\[90+86+71+100+\frac{98}{5}\]

What we need is an equation where the division happens last:

\[\dfrac{90+86+71+100+98}{5}\]

By using parentheses around the addition in our code, this problem can be fixed:

average = (90 + 86 + 71 + 100 + 98) / 5

7.3. Ausgabe von Variablen

../../_images/printer.svg

How can you print variables and text together? Say you’ve got a variable answer and you want to print it. Based on what we’ve learned so far, you can do this code:

answer = "bananas"
print(answer)

Aber das gibt nur bananas auf einer Zeile alleine aus. Nicht wirklich anschaulich. Was wenn wir haben wollten:

The answer is bananas

You can combine the answer with the additional text by using a comma. Here’s an example:

../../_images/banana.svg
answer = "bananas"
print("The answer is", answer)

That example was better. But it is missing punctuation. This code attempts to add a period at the end:

answer = "bananas"
print("The answer is", answer, ".")

Unfortunately, it doesn’t work quite right. We get an extra space before the period:

The answer is bananas .

The , adds a space when we use it in a print statement. We don’t always want that. We can instead use a + sign as shown in this example:

answer = "bananas"
print("The answer is" + answer + ".")

That gets rid of all the spaces:

The answer isbananas.

So we need to add a space INSIDE the quotes where we want it as shown here:

answer = "bananas"
print("The answer is " + answer + ".")

That works until you try an to print a variable that holds a number instead of text. Try this example:

answer = 42
print("The answer is " + answer + ".")

That code generates a brand new error we haven’t seen yet, a TypeError.

Traceback (most recent call last):
  File "C:/arcade_book/test.py", line 2, in <module>
    print("The answer is " + answer + ".")
TypeError: can only concatenate str (not "int") to str

What is the problem? The computer doesn’t know how to put text and numbers together. If you add two numbers 20 + 20 you get 40. If you add two strings "20" + "20" you get "2020", but the computer has no idea what to do with a combo of text and numbers. So the fix is to use the str function which converts the number to a string (text). Here’s an example:

answer = 42
print("The answer is " + str(answer) + ".")

Yes, this is a bit complex. But wait! There’s an easier way! We can print variables using a formatted string. Later we will spend a whole chapter on formatted strings, but here’s an example to get started.

answer = 42
print(f"The answer is {answer}.")

Note this example starts the string with an f before the quote, and the variable we want to print goes in curly braces. This is the way I recommend printing variables. Again, we’ll cover it in more detail in a later chapter.

7.4. Review

../../_images/girl-reading-book.svg

In this chapter we introduced the concept of using variables and using them in expressions. Expressions are made up of both variables, and operators which are used to tell the computers how to combine the values. We also showed how to print variables along with text. We will use this knowledge to create our own functions in the next chapter.

7.4.1. Review Questions

  1. What do computer languages use to store changing data?

  2. What do we call the = symbol in Python?

  3. When we store text into a variable, what is another name for the text?

  4. What are the rules around creating a good variable name?

  5. What is an expression?

  6. Give an example for each of the seven operators.

  7. What is integer division? Explain.

  8. What is modulus?

  9. Rewrite the expression v = 2(3.14r) so that it works in Python.

  10. What is the code to add 1 to x? (That is, actually change the value of x.)

  11. Show how to use the increment operator to add one to x.

  12. Give an example of printing a variable, including additional text that labels what it is.