Course outline · 0% complete

0/32 lessons0%

Course overview →

Reading Input

lesson 3-2 · ~11 min · 8/32

input() reads one line of text

Without input, every run of a program does exactly the same thing. input() is the first way your programs react to a user, and the read-a-line-then-convert shape you learn here returns unchanged when you read files and network data later.

input() pauses the program, waits for the user to type a line, and hands that line back as a string, always. Even if the user types 17, you get the string "17".

name = input()          # user types: Ada
age = int(input())      # user types: 17, converted to the int 17

That int(input()) combo is the standard way to read a number. Forgetting the conversion is the classic beginner bug: "17" + 3 crashes, and "17" * 3 gives "171717" (Python repeats strings when you multiply them).

In these exercises the Run panel supplies the typed lines for you, listed as stdin (standard input, the program's incoming text stream).

keyboard17input()"17" strint(...)17 intinput() always yields a string. Convert it yourself.
The typed line arrives as the string "17". int() turns it into a number you can do math with.

Code exercise · python

Run this. The stdin panel already contains the two lines the program will read: `Ada` and `17`.

Quiz

The user runs `x = input()` and types 5. What is `x * 2`?

Code exercise · python

Your turn. Read two whole numbers from input (one per line, stdin already has `7` and `10`). Print their sum as `Sum: 17`, then their average as `Average: 8.5` using an f-string with `:.1f`.

Code exercise · python

One more, combining input with lesson 1-3's `//` and `%`. Read a number of minutes (stdin has `150`) and print it as `2 h 30 min` using one f-string.