Input/Output and Type Casting
When writing programs, it’s essential to interact with users—taking input, showing output, and converting data types when necessary. Let’s break it down.
Output in Python
To display a message or result, Python uses the print()
function.
This is called an f-string, and it’s a clean way to combine text with variables.
Input in Python
To take user input, use the input()
function. It always returns the value as a string by default.
If the input needs to be a number, we must convert (cast) it.
Type Casting (Type Conversion)
Type casting means converting a value from one data type to another. Common conversions include:
Function | Converts to |
---|---|
int() |
Integer |
float() |
Decimal |
str() |
String |
bool() |
Boolean |
Example:
You must cast before performing math or logic on input values.
Be Careful:
If you try to convert invalid input like "abc"
to an int
, it will give an error.
Summary
print()
→ displays output.input()
→ reads user input as string.- Type casting is needed to convert data to
int
,float
,str
, etc. - Always ensure proper conversion when taking numeric input.