DE EN

Operators

Calculate, compare, logically combine — the mathematical foundation of programming.

40 Min Leicht

Lernziele dieses Kapitels

  • You use arithmetic operators for calculations and understand the difference between / and //
  • You compare values with ==, !=, <, > and combine conditions with and, or, not
  • You know the walrus operator := as a Python specialty
  • You expand PyBuddy with an XP calculator

Arithmetic Operators

In Python you can calculate just like on a calculator. You know the basic arithmetic from math — but there are some Python specialties:

  • +, -, * — Addition, Subtraction, Multiplication
  • / — Division (always returns float!)
  • // — Integer division (rounded down)
  • % — Modulo (remainder of a division)
  • ** — Exponentiation

Pro Tip

In games you often use % for wrap-around logic: When a player is at the end of the map and keeps walking, they appear back at the beginning.

Python
# Arithmetic operators at a glance
a = 17
b = 5

print(a + b)    # 22
print(a - b)    # 12
print(a * b)    # 85
print(a / b)    # 3.4  (always float!)
print(a // b)   # 3    (integer)
print(a % b)    # 2    (remainder)
print(a ** b)   # 1419857 (17 to the power of 5)

# Practice: XP calculation
basis_xp = 100
bonus = 1.5
gesamt = int(basis_xp * bonus + 25)
print(f"You receive {gesamt} XP!")
Ausgabe
22 12 85 3.4 3 2 1419857 You receive 175 XP!
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
print(17 // 5)   # 3
print(17 % 5)    # 2
print(2 ** 8)    # 256
JavaScript
console.log(Math.floor(17 / 5));  // 3
console.log(17 % 5);                // 2
console.log(Math.pow(2, 8));        // 256
Merke: Python has // and ** directly as operators. In JavaScript you need Math.floor() and Math.pow() (or ** with ES6).

Comparison Operators

Comparison operators check relationships between values and always return True or False. They are the heart of conditions (which you will deepen in the next chapter).

  • == — equal
  • != — not equal
  • <, > — less than, greater than
  • <=, >= — less than or equal, greater than or equal

Important: = is assignment, == is comparison. Beginners often confuse these!

Python
# Comparison operators
level = 10
print(level == 10)   # True
print(level != 5)    # True
print(level > 20)    # False
print(level <= 15)   # True

# Comparing strings
name = "PyBuddy"
print(name == "pybuddy")   # False (case sensitivity!)
print(name == "PyBuddy")   # True
Ausgabe
True True False True False True
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
print(level == 10)
print(name != "Boss")
JavaScript
console.log(level === 10);
console.log(name !== "Boss");
Merke: Python uses == and !=. JavaScript additionally has === and !== for strict type equality. Python compares values and types automatically and correctly.

Logical Operators

With logical operators you combine multiple conditions. They work like switches in circuit logic:

  • and — both conditions must be True
  • or — at least one condition must be True
  • not — reverses the value (True becomes False)
Python
# Logical operators
hp = 75
mana = 20
level = 12

# and: Both must be true
print(hp > 50 and mana > 10)   # True

# or: One is enough
print(hp > 100 or level > 10)  # True (level matches)

# not: Reversal
print(not hp > 50)             # False

# Combined
kann_zaubern = mana >= 30 and level >= 10
print(f"Can cast spell: {kann_zaubern}")  # False (mana too low)
Ausgabe
True True False Can cast spell: False
Python vs. JavaScript — Das kennst du schon!

Du kennst bereits JavaScript aus dem JS-Quest. Hier ist der direkte Vergleich:

Python
print(hp > 50 and mana > 10)
print(not hp > 50)
JavaScript
console.log(hp > 50 && mana > 10);
console.log(!(hp > 50));
Merke: Python writes out and, or, not — JavaScript uses symbols &&, ||, !.

The Walrus Operator :=

The walrus operator := (because it looks like a walrus ) is a Python specialty from version 3.8 onwards. It assigns a value to a variable and returns it at the same time.

This saves lines when you want to calculate a value and immediately check it.

Python
# Without walrus operator
eingabe = input("Enter a number: ")
zahl = int(eingabe)
if zahl > 10:
    print(f"{zahl} is greater than 10")

# With walrus operator (more compact!)
if (zahl := int(input("Enter a number: "))) > 10:
    print(f"{zahl} is greater than 10")

# Practice: Read text until it is not empty
while (name := input("Name (Enter to finish): ")):
    print(f"Hello {name}!")
Ausgabe
Enter a number: 15 15 is greater than 10 Enter a number: 15 15 is greater than 10 Name (Enter to finish): Max Hello Max! Name (Enter to finish):

Operators in Action: RPG Damage

Imagine you are programming a combat system for an RPG. You need to calculate damage, check if a hit was critical, and award XP. Operators are indispensable for this.

Python
# Combat system for a mini-RPG
basis_schaden = 25
kritisch = True
gegner_level = 8
spieler_level = 10

# Critical hit doubles the damage
schaden = basis_schaden * (2 if kritisch else 1)
print(f"Damage: {schaden}")

# Level advantage: 10% bonus per level difference
level_diff = spieler_level - gegner_level
if level_diff > 0:
    schaden = int(schaden * (1 + level_diff * 0.1))

print(f"Total damage: {schaden}")

# XP calculation with modulo
xp = schaden * 2
bonus_xp = xp % 50  # Remainder XP as bonus
print(f"XP: {xp}, Bonus XP: {bonus_xp}")
print(f"Level up: {xp >= 100}")
Ausgabe
Damage: 50 Total damage: 60 XP: 120, Bonus XP: 20 Level up: True

Warm-Up: Calculator

Write a program calculator.py that reads two numbers and performs all basic arithmetic operations.

Hinweis: a = float(input("First number: ")) b = float(input("Second number: ")) print(f"{a} + {b} = {a + b}") print(f"{a} - {b} = {a - b}") print(f"{a} * {b} = {a * b}") print(f"{a} / {b} = {a / b:.2f}") print(f"{a} // {b} = {a // b}") print(f"{a} % {b} = {a % b}") print(f"{a} ** {b} = {a ** b}")

Solution
a = float(input("First number: "))
b = float(input("Second number: "))

print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b:.2f}")
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
print(f"{a} ** {b} = {a ** b}")

Challenge: Dice Checker

Simulate a dice roll (number 1-6). Check with logical operators whether the number is even, odd, or a 6 (critical hit).

Hinweis: import random wurf = random.randint(1, 6) print(f"Roll: {wurf}") print(f"Even: {wurf % 2 == 0}") print(f"Critical hit: {wurf == 6}") print(f"Normal hit: {wurf >= 2 and wurf <= 5}")

Solution
import random
wurf = random.randint(1, 6)
print(f"Roll: {wurf}")
print(f"Even: {wurf % 2 == 0}")
print(f"Critical hit: {wurf == 6}")
print(f"Normal hit: {wurf >= 2 and wurf <= 5}")

PyBuddy Checkpoint: XP Calculator

PyBuddy gets an XP calculator: Base XP × Multiplier + Bonus. Use arithmetic operators and output the result formatted.

Hinweis: # pybuddy/main.py basis_xp = 100 multiplikator = 1.5 bonus = 50 gesamt_xp = int(basis_xp * multiplikator + bonus) print(f" Base XP: {basis_xp}") print(f" Multiplier: x{multiplikator}") print(f" Bonus: +{bonus}") print(f" Total XP: {gesamt_xp}")

Solution
# pybuddy/main.py
basis_xp = 100
multiplikator = 1.5
bonus = 50

gesamt_xp = int(basis_xp * multiplikator + bonus)
print(f"  Base XP: {basis_xp}")
print(f" Multiplier: x{multiplikator}")
print(f" Bonus: +{bonus}")
print(f" Total XP: {gesamt_xp}")
Learning Break

In World of Warcraft the server calculates thousands of operations every second: Damage = Weapon damage × Crit multiplier + Buff bonus. These are nothing but the arithmetic operators you just learned — just with more zeros behind them!

Zusammenfassung

  • Arithmetic: +, -, *, /, //, %, ** for all calculations
  • Comparisons: <code>==, !=, &lt;, &gt;, &lt;=, &gt;=</code> return True/False
  • Logic: and, or, not combine conditions
  • Walrus := assigns and returns — saves lines
  • Operators are the foundation for calculations and decisions