22 min read
Input and Type Conversion
Ask the user for data with input(), and turn the text it returns into numbers with int() and float().
input() Asks the User
Getting text from the userPython
name = input("Customer name: ")print("Thank you,", name)Expected output
Customer name: Nimali Thank you, Nimali
input() shows a prompt, waits for the user to type and press Enter, and returns what they typed. In this course, type the values in the Inputs box before pressing Run — one value per line, in order.
Put a space at the end of the prompt ("Customer name: ") so the answer does not touch the colon.
input() Always Gives Text
Press Run — what goes wrong?Python
price = input("Price: ")quantity = input("Quantity: ")print(price * quantity)This fails with a TypeError. input() always returns a string, so price is "250", not 250 — and Python cannot multiply two strings. You must convert the text to a number.
Converting with int() and float()
| Type conversion functions | ||
|---|---|---|
bill.py — working versionPython
item = input("Item: ")price = float(input("Price (LKR): "))quantity = int(input("Quantity: "))total = price * quantityprint(item, "total:", total)Expected output
Item: Dhal Price (LKR): 452.50 Quantity: 2 Dhal total: 905.0
bill.py as a flowchart
Read this flowchart as text
- Terminator: Start (then → INPUT item)
- Input/output: INPUT item (then → INPUT price)
- Input/output: INPUT price (then → INPUT quantity)
- Input/output: INPUT quantity (then → total = price × quantity)
- Process: total = price × quantity (then → OUTPUT item, total)
- Input/output: OUTPUT item, total (then → Stop)
- Terminator: Stop
Practice
More lessons in Python Programming · Next: Formatted Output · Previous: Comparison, Logical and Assignment Operators
