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 raisesEOFError. Bad text inint(input(...))raisesValueError; you will handle that withtry/exceptin Part 6.
Done here? The practice set for Part 2 โ 8 exercises with solutions โ is on the part page.