Learning Objectives – after this chapter you will be able to:
- Read user input with
input()and know that it always returns a string. - Convert values with
int(),float(),str(),bool()and others. - Distinguish implicit and explicit type conversion.
- Handle invalid input and format output with f-strings.
Reading Input with input()
input(prompt)shows the prompt, waits for the user to type and press Enter, and returns what was typed.- input() always returns a string, even if the user types a number. Convert it before doing arithmetic.
Program that reads input (run it in Colab and type values)
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # convert text to int
print("Hello", name)
print("Next year you will be", age + 1)Sample run (user input after the colon):
Enter your name: Ravi Enter your age: 19 Hello Ravi Next year you will be 20
Why conversion matters
a = "10" # what input() would return for 10 b = "20" print(a + b) # string concatenation! print(int(a) + int(b))
Output
1020 30
Reading two numbers on one line
x, y = map(int, input("Enter two numbers: ").split())
print("Sum =", x + y)Type Casting (Type Conversion)
| Function | Converts to | Example → Result |
|---|---|---|
int(x) | Integer (truncates decimals towards 0) | int("42") → 42, int(7.9) → 7 |
float(x) | Floating-point number | float("3.5") → 3.5, float(4) → 4.0 |
str(x) | String | str(25) → '25' |
bool(x) | True / False | bool(0) → False, bool("hi") → True |
list(x), tuple(x), set(x) | Collections | list("abc") → ['a', 'b', 'c'] |
ord(c) / chr(n) | Character ↔ Unicode code | ord("A") → 65, chr(97) → 'a' |
print(int("42") + 1)
print(int(7.9), int(-7.9)) # truncates towards zero
print(float("3.5") * 2)
print(str(25) + " apples")
print(bool(0), bool(""), bool("0"), bool([]))
print(list("abc"), tuple([1, 2]), set([1, 1, 2]))
print(ord("A"), chr(97))
print(int("1010", 2), int("ff", 16)) # binary and hexadecimal textOutput
43
7 -7
7.0
25 apples
False False True False
['a', 'b', 'c'] (1, 2) {1, 2}
65 a
10 255Implicit vs Explicit Conversion
- Implicit conversion – Python converts automatically to avoid losing data, e.g.
int + floatgives afloat. - Explicit conversion (type casting) – the programmer converts with functions such as
int(). - Python does not implicitly convert between strings and numbers:
"5" + 3raisesTypeError.
result = 5 + 2.5 # implicit: int -> float
print(result, type(result))
print(True + 3) # True behaves as 1
try:
print("5" + 3)
except TypeError as e:
print("Error:", e)
print("5" + str(3), int("5") + 3) # explicit fixesOutput
7.5 <class 'float'> 4 Error: can only concatenate str (not "int") to str 53 8
Handling Invalid Input
Converting text that is not a valid number raises ValueError. Use try / except to handle it gracefully.
for text in ["25", "2.5", "abc"]:
try:
print(int(text))
except ValueError:
print(f"'{text}' is not a valid integer")Output
25 '2.5' is not a valid integer 'abc' is not a valid integer
Formatting Output with f-strings
An f-string (formatted string literal, Python 3.6+) starts with f and places expressions inside { }. Format specifiers follow a colon.
name, marks, total = "Asha", 437, 500
percent = marks / total * 100
print(f"{name} scored {marks}/{total}")
print(f"Percentage: {percent:.2f}%")
print(f"{'Item':<8}|{'Qty':>5}")
print(f"{'Pen':<8}|{12:>5}")
print(f"{1234567:,}")Output
Asha scored 437/500 Percentage: 87.40% Item | Qty Pen | 12 1,234,567
Key Takeaways
input()always returns astr– convert before calculating.- Implicit conversion happens only between compatible numbers; strings and numbers need explicit casting.
- Catch
ValueErrorfor bad input; use f-strings for clean output.
Video : Data Reading (Input) and Type Casting
Question / Answer (15 questions)
Answer : input() always returns the text typed by the user as a string (str), even if the user types digits. It must be converted to a number before arithmetic.
Answer : Both values are strings, and + on strings performs concatenation (joining), not numeric addition. Converting them first, int("10") + int("20"), gives 30.
Answer : x, y = map(int, input().split()). split() breaks the text into parts at whitespace, and map(int, ...) converts each part to an integer.
Answer : Type casting (explicit type conversion) is converting a value from one data type to another using built-in functions such as int(), float(), str(), bool(), list() or tuple().
Answer : Implicit conversion is done automatically by Python, for example int + float produces a float. Explicit conversion is done by the programmer using functions such as int("5").
Answer : int() truncates towards zero, so int(7.9) is 7 and int(-7.9) is -7. It does not round to the nearest whole number.
Answer : Zero numbers (0, 0.0), empty strings (""), empty collections ([], (), {}, set()) and None are False. Everything else, including the string "0", is True.
Answer : Python does not implicitly convert between strings and numbers. Adding a str and an int raises TypeError: can only concatenate str (not "int") to str. Convert explicitly with str(3) or int("5").
Answer : ValueError is raised because "abc" is not a valid integer. It can be handled with try: n = int(text) except ValueError: print("Invalid number").
Answer : ord() returns the Unicode code point of a single character, e.g. ord("A") is 65. chr() returns the character for a code point, e.g. chr(97) is "a".
Answer : Pass the base as the second argument to int(): int("1010", 2) gives 10 and int("ff", 16) gives 255.
Answer : An f-string (formatted string literal, introduced in Python 3.6) is a string prefixed with f in which expressions inside curly braces are evaluated and inserted, for example f"Total: {price * qty}".
Answer : Use the format specifier .2f, for example f"{percent:.2f}" displays 87.4 as 87.40.
Answer : 4. bool is a subclass of int, and True behaves as the integer 1 in arithmetic.
Answer : Use list("abc"), which returns ['a', 'b', 'c'].
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes, questions and MCQs on this page are original explanations written for this course. The works listed below were consulted and are cited for attribution and further reading. Product names, logos and trademarks belong to their respective owners. Short quotations, where used, are marked and attributed.
- Python Software Foundation. (n.d.). Built-in Functions. The Python Standard Library. https://docs.python.org/3/library/functions.html
- Python Software Foundation. (n.d.). Input and Output. In The Python Tutorial. https://docs.python.org/3/tutorial/inputoutput.html
- Python Software Foundation. (n.d.). Errors and Exceptions. In The Python Tutorial. https://docs.python.org/3/tutorial/errors.html
- Smith, E. V. (2015). PEP 498 – Literal String Interpolation (f-strings). Python Enhancement Proposals. https://peps.python.org/pep-0498/
- Python Software Foundation. (n.d.). Built-in Types. The Python Standard Library. https://docs.python.org/3/library/stdtypes.html
- Matthes, E. (2023). Python Crash Course (3rd ed.). No Starch Press.