Python Type Casting

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’>”

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 convert the following string to a double.
4. Write a program to convert the following string to a decimal.
5. Write a program to convert any double value to a string using the ToString method and print the result:
6. Write a program to print the type of any variable:
7. Write a program to check whether the following two double values are equal using the == method and print the result:
8. Write a program to compare the following two double values using the == method and print the result:
9. Write a program to perform the following mathematical operations on the given integers and print the results:
int a = 10; int b = 5;
Subtraction
Addition
Multiplication
Division

Course Video

YouTube Reference :