Python Type Casting
Python allows you to convert one data type into another through type conversion (also known as type casting). There are two types of type conversion in Python:
Implicit Type Conversion: Python automatically converts one data type to another (from a smaller data type to a larger data type) without user intervention.
Explicit Type Conversion: The user explicitly converts one data type to another using predefined functions which are as follows:
Function | Description | Example |
---|---|---|
int() | Converts a value to an integer | int(12.9) → 12 |
float() | Converts a value to a float | float(10) → 10.0 |
str() | Converts a value to a string | str(123) → “123” |
1. int(): Converts a string to an integer
age = 25 # Here, ‘age’ is a variable, and ’25’ is its value.
roll_no_string = “123”
roll_no = int(roll_no_string) # roll_no is 123
print(roll_no) # Output: 123
2. float(): Converts a string to a float and double both by value
weight_string = “55.5”
weight = float(weight_string) # weight is 55.5
print(weight) # Output: 55.5
pi_string = “3.14”
pi_value = float(pi_string) # pi_value is 3.14
print(pi_value) # Output: 3.14
3. str(): Converts a number to a string
pi_value = 3.14159
pi_string_value = str(pi_value)
print(“ToString() output: ” + pi_string_value)
# Output: “ToString() output: 3.14159”
4. type(): Returns the type of the current variable
pi_value = 3.14159
print(type(pi_value))
# Output: <class ‘float’>”
Course Video
Course Video English
Task:
1. Write a program to convert the following string to an integer.
2. Write a program to convert the following string to a float.
3. Write a program to print the type of any variable:
4. Write a program to check whether the following two float values are equal using the == method and print the result:
5. Write a program to perform the following mathematical operations on the given integers and print the results:
a = 10; b = 5;
Subtraction
Addition
Multiplication
Division
Task Video
YouTube Reference :
Type casting in Python refers to converting one data type into another.
Explicit casting requires the programmer to manually convert types using functions like int(), while implicit casting is automatically handled by Python when converting lower data types to higher ones.
Implicit and explicit.
Use the list() function to convert a different data type into a list.
Use list() to convert another data type to a list.
Yes, Python performs implicit type casting in certain situations.
No, self must be explicitly passed as the first argument in methods inside a class.
Yes, implicit type conversion occurs in Python when necessary.
Identifiers should be descriptive, lowercase or underscored, and avoid reserved words. Example: total_count, calculate_sum.
Constants are written in uppercase letters with underscores between words, such as MAX_SIZE or PI_VALUE.