Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 02 / Topic 7 of 10

input()

input() shows a message, waits for the user to type, and always returns a string. Cast it if you need a number.

Real-world example: Ask how many people are at the table.

>>> people = input("How many people? ")
How many people? 4
>>> people
'4'
>>> people * 2
'44'
>>> int(people) * 2
8

Mini preview: functions (full lesson in Part 5). Exercises in this part use tiny functions, so here is the pattern. def gives a name to some steps; return sends the answer back. The : float and -> float parts are optional type hints (labels for humans, Python does not check them).

# Pattern used in this repo: logic in a function, input only at the edge
def per_person(total: float, people: int) -> float:
    return total / people

print(per_person(1200, 4))   # 300.0
print(per_person(999, 3))    # 333.0
# Real use: print(per_person(float(input("Total: ")), int(input("People: "))))

๐Ÿ” Going deeper: input() removes the Enter key's newline from what it returns. If there is nothing to read (for example, input is piped from an empty file), it raises EOFError. Bad text in int(input(...)) raises ValueError; you will handle that with try/except in Part 6.

Done here? The practice set for Part 2 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide