Type Casting
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
Type Casting
Definition: Type casting is the process of converting the value of one data type (such as a string, integer, or float) into another data type.
Why: Casting is essential for basic data handling, especially when you receive data in one format (like text from a user) but need to use it in another (like a number for calculations).
Syntax
int(value)- Converts to an integer.float(value)- Converts to a floating-point number.str(value)- Converts to a string.
Example
age = "25"
new_age = int(age)
print(new_age)
print(type(new_age))
Explanation
- The variable
ageis initially a string because it is enclosed in quotes. - The
int(age)function converts that string into the integer25. - The
type()function confirms thatnew_ageis now an integer (<class 'int'>).
Key Notes
- You can only cast a string to an integer if the string contains a valid number (e.g.,
int("10")works, butint("apple")will cause an error). - Converting a float to an integer will "truncate" the number, meaning it removes the decimal part without rounding (e.g.,
int(3.9)becomes3).
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute