Getting input (and why it is different here)
Every program so far has known its own data. Real programs ask. input() is
how Python does that from a terminal, and it has exactly one behaviour that
catches everybody.
name = input("What is your name? ")
print(f"Hello, {name}")
Run that in a terminal and it prints the question, waits, and continues once you press Enter.
The lessons on this site run in your browser
Every runnable block on WasiLearn Code executes inside your own browser, not on
a server. There is no terminal attached, so there is nothing for input() to
read from — it would hang forever waiting for a keyboard that is not there.
So the examples below assign the value directly instead:
name = "Ayesha" # stands in for input("What is your name? ")
print(f"Hello, {name}")
Hello, Ayesha
That is not a workaround for a limitation so much as good practice anyway. Separating "get the value" from "do something with the value" makes the second part testable without a human typing.
To try input() properly, save a .py file and run it with
python filename.py from a terminal on your own machine.
input() always returns a string
This is the rule, and it has no exceptions. Even when the person types nothing but digits, you get text.
age = "16" # exactly what input() would have given you
print(type(age))
<class 'str'>
Which means the obvious next line does not work:
age = "16"
next_year = age + 1
print(next_year)
The program stops:
TypeError: can only concatenate str (not "int") to str
Python refuses rather than guessing. JavaScript in the same position would
produce "161" and carry on, which is worse — a wrong answer that travels.
Convert as it arrives
The fix is to wrap the call, so the variable holds a number from the very first line:
age = int(input("Your age: "))
Read it inside out: input() gets the text, int() turns it into a whole
number, and age holds the result. Every use afterwards is arithmetic.
age = int("16")
print(age + 1)
print(type(age))
17 <class 'int'>
Use float() when decimals are possible — a weight, a price, a temperature:
weight = float("72.5")
print(weight * 2)
145.0
When the person types something else
int() fails loudly on text it cannot read, and that failure will happen,
because people type things.
print(int("twelve"))
ValueError: invalid literal for int() with base 10: 'twelve'
A crash is honest, and it is still a crash. In a program someone else uses, you check first:
typed = "twelve"
if typed.isdigit():
age = int(typed)
print(f"Next year you will be {age + 1}")
else:
print("Please type your age using digits.")
Please type your age using digits.
isdigit() is the quick check for whole numbers. Be aware of its limits: it
is False for "-5" and for "3.5", because neither the minus sign nor the
dot is a digit. For anything beyond simple counts, the better pattern is to
try the conversion and catch the failure, which
the exceptions lesson covers.
Asking until the answer is usable
A single check rejects bad input. A loop keeps asking for good input.
while True:
typed = input("Your age: ")
if typed.isdigit():
age = int(typed)
break
print("Digits only, please.")
print(f"Next year you will be {age + 1}")
while True repeats forever and break is the only way out, which is taken
only once a valid number has been converted. That shape — loop, validate,
break — is the standard way to insist on good input, and
the loops lesson covers the mechanics.
Whitespace and case
Anything typed arrives with whatever spacing the person used, and trailing spaces are invisible.
typed = " Karachi \n"
print(repr(typed))
print(repr(typed.strip()))
print(typed.strip().lower())
' Karachi \n' 'Karachi' karachi
repr() shows the string as Python sees it, quotes and escape characters
included. It is the fastest way to see a stray space or newline that print()
hides.
.strip() removes whitespace from both ends. Strip before you compare
anything a person typed, or "Karachi " will fail to match "Karachi" for
reasons invisible on screen.
For a yes-or-no answer, strip and lower in one go:
answer = " YES "
if answer.strip().lower() in ("y", "yes"):
print("Confirmed.")
else:
print("Cancelled.")
Confirmed.
Several values at once
split() turns one typed line into a list:
typed = "chai paratha samosa"
items = typed.split()
print(items)
print(len(items))
['chai', 'paratha', 'samosa'] 3
With no argument, split() breaks on any run of whitespace, which handles
double spaces without complaint. Pass a separator for structured input:
typed = "12,45,7"
numbers = [int(part) for part in typed.split(",")]
print(numbers)
print(sum(numbers))
[12, 45, 7] 64
That bracket form is a list comprehension, covered in its own lesson. For now, read it as "int(part) for every part after splitting".
The habit
Convert and clean at the boundary. The line that reads a value is the line that should strip it, lower it and convert it. After that, the rest of your program is working with real numbers and real text, and every bug you have left is a bug in your logic rather than in your input handling.
Next: making decisions with if puts these values to work, and types and converting has the full conversion rules.
Prefer learning with a teacher?
WasiLearn Academy runs small-group classes covering this material, online and in Karachi.
See the classes