LEARN PYTHON | Input And Type Conversion

Lesson objective

Use input() to collect text, convert suitable responses with int() or float(), and explain conversion errors and the difference between text and arithmetic.

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.

MATCH THE PYTHON TERM TO ITS MEANING

Terminology

Terminology

input()

Collects a line of user input and returns text.

Prompt

A message requesting a specific response.

Response

The text typed by the user.

Conversion

Producing a value in another type from suitable data.

int()

Converts suitable input to an integer.

float()

Converts suitable input to a floating-point number.

str()

Produces a text representation.

Concatenation

Joining strings end to end.

TypeError

An operation receives an unsuitable type.

ValueError

The type is acceptable but the value is unsuitable, such as invalid numeric text.

Empty string

Text containing zero characters.

Whitespace

Spaces, tabs and similar spacing characters.

strip()

A string method returning text without surrounding whitespace.

Method

An operation associated with a value or object.

Nested call

One function call supplies the value needed by another.

Traceback

A report connecting an exception to the executing code.

Numeric prompt

A prompt explaining the expected number and units.

Input assumption

A stated condition the initial program relies on.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which describe input()?
2. Which suit int()?
3. Which suit float() in these examples?
4. Which describe nested conversion?
5. Which describe string joining?
6. Which describe empty input?
7. Which describe strip()?
8. Which are sensible testing habits?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Explain why input of 12 is not automatically numeric.

2. Trace int(input("Count: ")) for response 4.

3. Compare "12" + "3" with 12 + 3.

4. Explain int("2.5").

5. Write a useful measurement prompt.

6. Explain why strip does not validate a count.

7. Explain why bool("False") is misleading for yes/no input.

8. Describe two useful tests for a trip report.

CODE IT | YOUR INDEPENDENT CHALLENGE

Create a trip report with a name, destination, day count and daily distance. Convert suitable inputs and show a predicted total.

Work in your Python editor. Keep a working version, explain one design choice and record at least two tests. Use the Learn tab for worked examples before comparing your result.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for Input And Type Conversion is coming soon. Complete the matching task and written questions in your exercise book.