Definition
Why does adding the input "5" to "5" give "55" instead of 10?
input() shows a prompt, waits for the user to type, and returns what they typed as a string. Type conversion, also called casting, changes a value from one type to another with functions such as int(), float(), str() and bool().
In simple words
Everything typed on a keyboard arrives as text, even digits. If someone types 15 for their age, Python gets "15". To do maths with it, convert it: int("15") is the number 15. To join a number into a sentence, convert the other way: str(15).
Overview
- input() pauses the program, shows a prompt and returns whatever the user types as a string.
- Because input is always text, numbers must be converted with int() or float() before arithmetic.
- Converting a value from one type to another is called type conversion or type casting.
- A conversion that cannot make sense, such as int("twelve"), raises ValueError.
- split() breaks one line of input into parts, and map() converts every part at once.
- Programs that accept user input should validate it and ask again if it is wrong.
Why it matters
Data from users, files and websites usually arrives as text. Converting it correctly, and handling text that isn't a valid number, is a daily task in every AI project.
Key terms
- input()
- A function that shows a prompt and returns what the user types, always as a string.
- Type conversion
- Changing a value from one type to another, such as int("42").
- Implicit conversion
- A conversion Python does automatically, such as int plus float giving float.
- ValueError
- The error raised when a value has the right type but an invalid content, such as int("abc").
- Validation
- Checking that input is sensible before using it.
- Whitespace
- Spaces, tabs and new lines, often stripped from input with .strip().
Types
Python changes types in two ways, automatically or on request, and there are a few common conversion patterns for input. These are the types.
1. Implicit conversion (coercion)
Python changes a type automatically when it is safe and no information is lost.
- How it works: In mixed arithmetic the narrower type is widened: bool to int, int to float, float to complex.
- Example: 3 + 2.5 gives 5.5 (a float); True + 1 gives 2.
- When to use it: Rely on it for numeric calculations, but remember Python never silently turns text into numbers: "3" + 2 is a TypeError.
2. Explicit conversion (casting)
You call a type's name as a function to convert a value yourself.
- How it works: int(), float(), str() and bool() build a new value of that type; int() of a float cuts off the decimal part.
- Example: int("42") is 42, float("3.5") is 3.5, str(99) is "99", int(7.9) is 7, bool("") is False.
- When to use it: Use it whenever data arrives as text, from input(), files or web forms, and before joining numbers into strings.
3. Parsing several values from one line
Reading many numbers typed on one line and converting them together.
- How it works: split() turns "70 85 92" into ["70", "85", "92"]; map(int, ...) converts each; list() or unpacking stores them.
- Example: a, b = map(int, input("Two numbers: ").split())
- When to use it: Use it for compact input of marks, coordinates or dates, common in practice problems.
4. Converting between collections
Turning one collection type into another with list(), tuple(), set() or dict().
- How it works: Each function builds a new collection from any iterable; set() removes duplicates, and dict() needs key-value pairs.
- Example: set([3, 3, 5]) is {3, 5}; list("abc") is ['a', 'b', 'c']; dict([("a", 1)]) is {'a': 1}.
- When to use it: Use it to remove duplicates, make data changeable or unchangeable, or build lookup tables.
Explained in detail
input() always gives text
Whatever the user types, input() returns it as a string, even if it looks like a number. If a learner types 15 when asked for their age, age = input("Age: ") stores "15", and age + 1 raises a TypeError. You must convert it first: age = int(input("Age: ")). The same rule applies to text read from files and web forms, so learning to convert and check input is one of the most useful habits in practical programming.
Conversion functions
| Call | Result | Watch out |
|---|---|---|
| int("42") | 42 | int("4.5") fails; convert to float first |
| int(4.9) | 4 | Cuts off the decimal part, does not round |
| float("3.5") | 3.5 | float("3,5") fails: use a point, not a comma |
| str(99) | "99" | Needed before joining a number to text with + |
| bool("False") | True | Any non-empty string is True, even "False" |
| round(2.675, 2) | 2.67 | Float storage can make rounding surprising |
Implicit conversion
Python converts automatically only when it is safe and unambiguous. Mixing int and float in arithmetic produces a float: 3 + 0.5 is 3.5. Dividing two ints with / always produces a float: 10 / 2 is 5.0. True and False act as 1 and 0 in arithmetic, so sum([True, False, True]) is 2, a neat way to count how many conditions are true. But Python will never silently turn text into a number or a number into text; you must ask.
Validating input
- Strip spaces first: name = input().strip().
- Check text before converting: "42".isdigit() is True, "4a".isdigit() is False.
- Check ranges after converting: a mark should be between 0 and 100.
- Ask again in a loop until the input is valid, or catch ValueError with try and except, which you will learn later.
Validation is not only about avoiding crashes. In real systems, unchecked input is a major source of security problems, because attackers deliberately type values the programmer did not expect. The habit of checking every input starts here.
In data work you will meet the same problem at a larger scale. When pandas reads a CSV file, a column of numbers that contains even one stray word, such as "absent", is read as text, and averages fail. Checking and converting types is one of the first steps in cleaning any data set, so the habit you build with input() carries straight into AI projects.
How it works
| Conversion | Result | Note |
|---|---|---|
| int("15") | 15 | Text to whole number |
| float("2.5") | 2.5 | Text to decimal |
| int(3.9) | 3 | Cuts off the decimal, doesn't round |
| str(42) | "42" | Number to text |
| int("hello") | ValueError | Not a valid number |
In code
The age arrives as text, is converted to a number, used in maths, then converted back to text for the message.
# On your computer: age_text = input("Your age: ")
age_text = "15"
print("Typed:", repr(age_text), "of type", type(age_text).__name__)
age = int(age_text)
print("In 10 years you will be", age + 10)
print("Days lived, roughly:", age * 365)
message = "Age " + str(age) + " confirmed"
print(message)
print(int(3.9), float("2.5"), bool(0), bool("hi"))Output
Typed: '15' of type str In 10 years you will be 25 Days lived, roughly: 5475 Age 15 confirmed 3 2.5 False True
Try it yourself
Predict the result
Match each expression to what it gives.
- "5" + "5"
- int("5") + 5
- int(7.8)
- str(3) + "D"
- float("4")
Common mistakes
- Forgetting that input() always returns a string.
- Expecting int() to round. int(3.9) is 3.
- Converting text that isn't a number, such as int("twelve"): ValueError.
Check yourself
Summary
- input() returns text, always.
- int(), float(), str() and bool() convert between types.
- Converting invalid text raises ValueError.
Finished reading?
Sources: W3Schools: Python Casting