input() and type conversion
input() pauses the program, waits for the user to type a line, and hands that line back to you.
name = input()
print(f"Hi {name}!")
You can give it a prompt to show first, like input("Your name: "). In this course the exercises feed input automatically (you will see it in the stdin box), so we mostly call input() with no prompt to keep the output clean.
Now the trap that catches literally everyone: input() always gives you a string. Even if the user types 5, you get the text "5", not the number 5.
a = input() # user types 5
b = input() # user types 5
print(a + b) # 55 string + string glues them together
To do maths, convert the string first:
int("5")gives the int5.float("2.5")gives the float2.5.str(5)goes the other way and gives the string"5".
Usually you convert straight away, in the same line:
age = int(input())
If the text cannot be converted, Python stops with a ValueError. int("hello") fails, and so does int("2.5"), because int() wants a whole number written as digits. (int(2.5) with an actual float is fine though; it chops off the decimal part and gives 2.)
You can check what type something is with type(): type("5") is str, type(5) is int. When a program does something weird with numbers, printing the type is a great first step.
Try it yourself
Edit it. Break it. Run it again.name = input("What's your name? ")
age = int(input("How old are you? "))
print()
print(f"Hi {name}! In 5 years you will be {age + 5}.")
raw = "5"
print(raw + raw, "vs", int(raw) + int(raw))
print(type(raw), type(int(raw)))
Your turn
Type it yourself. That is the whole trick.1Add two numbers
The program reads two whole numbers, one per line. Print their sum. With the input 7 and 5, the output should be 12.
The checker feeds this input to your program.
a = input() b = input() print(a + b)
2Ticket price
Read a number of tickets (a whole number) and a price per ticket (which can have decimals), each on its own line. Print the total with an f-string so the output is exactly Total: 37.50 for 3 tickets at 12.5 each. Show exactly two decimal places.
The checker feeds this input to your program.
tickets = input()
price = input()
print(f"Total: {tickets}")