input: the program asks, then waits
input("How many cups? ") shows the question, waits for the user to type and press Enter, and gives back what was typed- Store the answer in a variable:
cups = input("How many cups? ") - The answer is always text: typing 19 gives
"19", not the number 19 - End the question with a space, so the user's answer does not stick to it
Converting
int("19") gives the whole number 19float("2.5") gives the decimal number 2.5int("2.5") stops with a ValueError: int reads whole numbers only; use float for a decimal
f-strings (format strings)
- Put
f right before the opening quote, and a variable's name (or a sum) in curly brackets f"Total: ₹{total}" shows Total: ₹135 when total holds 135- Without the
f, the brackets and the name print as plain text - A calculation with a decimal in it gives a decimal: 60 × 2.5 shows as 150.0
Convert at the door
- A whole number:
quantity = int(input("How many? ")) - A decimal:
kilos = float(input("How many kg? ")) - From then on, the variable holds a number; no converting later
The trap
- "input gives me a number if the user types digits":
age + 1 then stops with a TypeError, and age + "1" quietly shows 191 - Instead: input always gives text, so convert it with int or float on the same line you ask
Code to try (type it in Google Colab or Visual Studio Code, run it and answer the question)
age = input("Age? ")
print(age + 1)
Then fix it:
age = input("Age? ")
print(int(age) + 1)
Priya's shop bill:
price = 45
quantity = int(input("How many? "))
print(f"Total: ₹{price * quantity}")
Ravi's tomatoes:
price = 60
kilos = float(input("How many kg? "))
print(f"Total: ₹{price * kilos}")