I1 · Python Programming for AI

Input and Type Conversion

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().

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

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).

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.

How it works

ConversionResultNote
int("15")15Text to whole number
float("2.5")2.5Text to decimal
int(3.9)3Cuts off the decimal, doesn't round
str(42)"42"Number to text
int("hello")ValueErrorNot 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.

age_calculator.py
# 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

Question 1

1. What type does input() return?

Question 2

2. int("20") + 1 is…

Question 3

3. int(9.99) is…

Summary

  • input() returns text, always.
  • int(), float(), str() and bool() convert between types.
  • Converting invalid text raises ValueError.

Finished reading?

Sources: W3Schools: Python Casting