Learn
01.4 | INPUT AND TYPE CONVERSION
01 | GIVE THE USER A TURN
Until now the values were written directly into the source. input() pauses the program while the user types a response and presses Enter. Its argument can be a prompt explaining what to enter.
The returned response is a string. Python removes the input line’s trailing newline, but it does not automatically decide that digits should become a number.
The assignment stores the returned text under the name username. The next statement runs after the input completes.
username = input("What is your first name? ")
print(f"Hello, {username}!")02 | PROMPTS ARE PART OF THE INTERFACE
A helpful prompt says what information is needed and, when relevant, its units. “Enter distance in kilometres: ” is clearer than “Number?”. The space after the colon leaves a readable gap before the response.
When a program seems to stop after printing a prompt, it may be waiting normally. In IDLE type into the shell. In VS Code’s Python run workflow type into the terminal, not the source editor or a read-only output panel.
A prompt is output; the response is input. These are different directions of information flow.
03 | DIGITS ARRIVE AS TEXT
Suppose the user enters 12. The returned value is "12", not the integer 12. If the program adds that string to another string, + joins them. It does not perform numeric addition.
Combining incompatible kinds, such as a string plus an integer, can raise TypeError. The solution is to choose the representation needed by the task, rather than adding quotes to every value until the error disappears.
first = input("First number: ")
second = input("Second number: ")
print(first + second)EXPECTED OUTPUT
If the inputs are 12 and 3, the output is 123.
04 | INT CONVERTS SUITABLE WHOLE-NUMBER TEXT
Use int() when the task expects a whole number. The call int("12") returns the integer 12. You can store the text first and convert it on another line, which makes the steps easy to inspect.
The conversion needs text in a suitable integer form. "12.5", an empty response or "twelve" is not valid integer text for int() and raises ValueError. Converting is not the same as proving the value meets every application rule.
count_text = input("Number of tickets: ")
count = int(count_text)
print("Tickets after adding one:", count + 1)05 | FLOAT ACCEPTS FRACTIONAL NUMBER TEXT
Use float() when a measurement or calculation may have a fractional part. float("2.5") produces 2.5. It also accepts whole-looking numeric text such as "2" and returns 2.0.
For the beginner programs here, ask for plain numbers using a decimal point. Do not include a unit, currency sign or thousands comma in the response. "2.5 km" is useful for a human reader but is not suitable numeric text for this call.
The unit belongs in the prompt and output label; the stored number represents the quantity.
distance = float(input("Distance in kilometres: "))
print("Distance in metres:", distance * 1000)06 | READ A NESTED CALL FROM THE INSIDE
In float(input(...)), input runs first because its returned value is needed by float. Then float converts that text; assignment gives the converted value a name.
This compact form does the same work as two separate lines. Use the separate form while learning if you want to inspect the raw response. Compact code is useful only when its meaning stays clear.
distance_text = input("Distance in kilometres: ")
distance = float(distance_text)
# Equivalent compact form for another response
other_distance = float(input("Another distance in kilometres: "))07 | STR CONVERTS A VALUE TO TEXT
str() creates a text representation of a value. It can help when deliberately joining text, though comma-separated print and f-strings often make reporting simpler.
Converting 12 to "12" does not change what you meant to measure, but it changes which operations are available. Text joining is different from arithmetic.
points = 12
print("Points: " + str(points))
print(f"Points: {points}")EXPECTED OUTPUT
Points: 12 Points: 12
08 | EMPTY INPUT AND SPACES MATTER
Pressing Enter without typing returns an empty string. int("") and float("") fail. input does not remove ordinary leading and trailing spaces from a name.
The string method strip() returns a version with surrounding whitespace removed. A method is an operation associated with a value; the dot connects the string to its method. Save the returned result if you want to use it.
Numeric conversion accepts some surrounding whitespace, but strip is useful for names and later validation. It does not make "two" into a numeric value.
username = input("First name: ").strip()
print(f"Hello, {username}!")09 | A CONVERSION ERROR IS USEFUL EVIDENCE
When unsuitable text reaches int or float, ValueError identifies a failed conversion. Read the last part of the traceback, then find the source line. A traceback is the report linking an error to the executing code.
These first programs assume the user follows the stated numeric instructions. Enter an invalid value deliberately to learn what the failure looks like. Handling it gracefully requires exception handling or a suitable validation strategy, introduced later.
Also, bool("False") is True because a non-empty string is truthy; it does not parse the word False as a Boolean response. Do not use that shortcut to interpret yes/no input.
10 | TRY TEXT JOINING AND NUMBER CONVERSION
Enter two ordinary decimal numbers below. The teaching demo shows the string join and numeric sum separately. It recognises a restricted decimal format for this activity; it is not a full implementation of every numeric form Python accepts.
11 | BUILD AN INTERACTIVE MINI REPORT
Ask for a first name, a whole-number project count and a fractional number of practice hours. Convert the numeric responses appropriately, then print a readable summary.
Predict which line will fail if project count receives "2.5". Explain why practice hours can accept that same text. For testing, separate valid examples from deliberate conversion failures.
username = input("First name: ").strip()
projects = int(input("Completed projects (whole number): "))
hours = float(input("Practice hours: "))
print(f"{username} completed {projects} projects in {hours} hours.")12 | INDEPENDENT CHALLENGE: A TRIP REPORT
Write trip_report.py. Ask for a traveller’s first name, a destination, a whole-number day count and a daily distance in kilometres. Print a report and the total distance.
Assume sensible non-negative numeric responses for this first version. Test at least two ordinary examples and one zero distance. Then document what happens for blank numeric input and a word such as ten.
Extension: strip the name and destination, and label every quantity with its unit. Explain why the prompts guide the user but do not enforce all the rules.