DE EN

Input, Output & Strings

Interact with the user, master text, and use Python strings like a pro.

45 Min Leicht

Lernziele dieses Kapitels

  • You use input() for user input and convert types correctly
  • You master f-Strings for formatted output
  • You apply string methods practically
  • You let PyBuddy ask the user for their name

input() — The Program Listens to You

So far, we've only output text (print). Now you'll learn to input (input). The program pauses and waits until the user types something.

IMPORTANT: input() always returns a string. Even if someone enters 16, for Python it's "16". For numbers, you must convert with int() or float().

Python
name = input("Wie heißt du? ")
print(f"Hallo {name}!")

# Zahlen müssen umgewandelt werden!
alter = int(input("Wie alt bist du? "))
print(f"In 10 Jahren bist du {alter + 10}.")
Ausgabe
Wie heißt du? Max Hallo Max! Wie alt bist du? 16 In 10 Jahren bist du 26.
Python vs. JavaScript — Das kennst du schon!

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

Python
name = input("Name: ")
alter = int(input("Alter: "))
JavaScript
let name = prompt("Name:");
let alter = parseInt(prompt("Alter:"));
Merke: Python uses `input()` and `int()` directly — JavaScript needs `prompt()` and `parseInt()`. Also: `input()` waits in the terminal, `prompt()` opens a popup.

f-Strings — Python's Magical Text Processing

In JavaScript, you know Template Literals with backticks: `Hallo ${name}`. In Python, there are f-Strings — even easier and faster.

Simply write an f before the string and put variables in curly braces. Done!

Python
# f-Strings in Python
name = "Max"
alter = 16

print(f"Hallo {name}!")
print(f"Du bist {alter} Jahre alt.")
print(f"In 5 Jahren bist du {alter + 5}.")

# Formatierung
preis = 19.995
print(f"Preis: {preis:.2f}€")  # 2 Dezimalstellen
Ausgabe
Hallo Max! Du bist 16 Jahre alt. In 5 Jahren bist du 21. Preis: 20.00€
Python vs. JavaScript — Das kennst du schon!

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

Python
print(f"Hallo {name}!")
print(f"Preis: {preis:.2f}€")
JavaScript
console.log(`Hallo ${name}!`);
console.log(`Preis: ${preis.toFixed(2)}€`);
Merke: Python: `:.2f` formats directly in the f-string. JavaScript: `.toFixed(2)` is a method. Both round to 2 decimal places.

String Methods — Manipulating Text

Strings in Python are objects with built-in methods. You can change them, split them, search them, and format them — without having to write code yourself.

Python
text = "  Python ist mega cool  "

# Formatierung
print(text.upper())       # PYTHON IST MEGA COOL
print(text.lower())       # python ist mega cool
print(text.strip())       # Leerzeichen entfernt

# Suchen & Ersetzen
print(text.replace("cool", "OP"))
print(text.find("mega"))  # Position: 15

# Teilen & Verbinden
woerter = text.split()    # ["Python", "ist", "mega", "cool"]
print(woerter)
print("-".join(woerter))  # Python-ist-mega-cool
Ausgabe
PYTHON IST MEGA COOL python ist mega cool Python ist mega cool Python ist mega OP 15 ['Python', 'ist', 'mega', 'cool'] Python-ist-mega-cool
Python vs. JavaScript — Das kennst du schon!

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

Python
text.upper()
text.replace("alt", "neu")
text.split()
JavaScript
text.toUpperCase()
text.replace("alt", "neu")
text.split(" ")
Merke: The methods are almost identical! Only `strip()` in Python vs `trim()` in JavaScript and `find()` vs `indexOf()` differ slightly.

String Slicing — Splitting Text Like a Pro

With Slicing, you can cut out parts of a string — similar to JavaScript arrays, but even more intuitive. The syntax is: text[start:stop:step].

Python
name = "Python"

print(name[0])      # P (erstes Zeichen)
print(name[-1])     # n (letztes Zeichen)
print(name[0:4])    # Pyth (Zeichen 0-3)
print(name[2:])     # thon (ab Index 2)
print(name[:4])     # Pyth (bis Index 3)
print(name[::2])    # Pto (jedes 2. Zeichen)
print(name[::-1])   # nohtyP (rückwärts!)
Ausgabe
P n Pyth thon Pyth Pto nohtyP
Python vs. JavaScript — Das kennst du schon!

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

Python
name[0:4]    # Slicing direkt
name[::-1]   # Rückwärts
JavaScript
name.slice(0, 4);  // Methode nötig
name.split("").reverse().join("");  // Kompliziert!
Merke: Python slicing is more elegant! `[::-1]` reverses a string instantly — in JavaScript, you need `split().reverse().join()`.

Warm-Up: Mad Libs Game

Write a Mad Libs game: The program asks for an adjective, a noun, and a verb, and inserts them into a funny sentence.

Hinweis: adjektiv = input("Ein Adjektiv: ") nomen = input("Ein Nomen: ") verb = input("Ein Verb: ") print(f"Der {adjektiv}e {nomen} hat beschlossen, {verb} zu gehen.")

Solution
adjektiv = input("Ein Adjektiv: ")
nomen = input("Ein Nomen: ")
verb = input("Ein Verb: ")

print(f"Der {adjektiv}e {nomen} hat beschlossen, {verb} zu gehen.")

Challenge: Password Generator

Create a simple password generator. The user enters their name and birth year. The password is composed of: uppercase letter of the name + lowercase letters + birth year + "!"

Hinweis: name = input("Dein Name: ") jahr = input("Geburtsjahr: ") passwort = name[0].upper() + name[1:].lower() + jahr + "!" print(f"Dein Passwort: {passwort}")

Solution
name = input("Dein Name: ")
jahr = input("Geburtsjahr: ")

passwort = name[0].upper() + name[1:].lower() + jahr + "!"
print(f"Dein Passwort: {passwort}")

PyBuddy Checkpoint: Interactive Greeting

PyBuddy should ask the user for their name and greet them personally. Use input() and f-strings for a professional greeting.

Hinweis: # pybuddy/main.py nutzer_name = input(" Wie heißt du? ") print(f"\n Hallo {nutzer_name}!") print(f"Schön, dass du da bist, {nutzer_name}.") print("Ich bin PyBuddy — dein digitaler Assistent.") print(f"Bereit für deine Befehle, {nutzer_name}? ")

Solution
# pybuddy/main.py
nutzer_name = input(" Wie heißt du? ")

print(f"\n Hallo {nutzer_name}!")
print(f"Schön, dass du da bist, {nutzer_name}.")
print("Ich bin PyBuddy — dein digitaler Assistent.")
print(f"Bereit für deine Befehle, {nutzer_name}? ")
Learning Break

In Discord bots, input() is the heart: When someone types !wetter Wien, the bot reads the input, processes it, and replies. That's exactly what you're learning right now — and in Chapter 11, you'll build your first API call!

Zusammenfassung

  • input() reads user input — always as a string!
  • f-Strings: f"Hallo {name}" — the simplest text formatting
  • String methods: upper(), lower(), strip(), replace(), split(), join()
  • Slicing: text[0:5] extracts parts — text[::-1] reverses
  • PyBuddy now asks for the user's name