3-4. Type Conversion

In Python, you can specify a type for a variable using casting, which involves converting a value from one type to another. Python, being an object-oriented language, uses classes to define data types, including its primitive types. Casting is performed using constructor functions like int(), float(), and str().

Casting to Integer

The int() function converts a value to an integer. This can be done from an integer literal, a float literal (by removing all decimals), or a string literal (provided the string represents a whole number).

Casting to Float

The float() function converts a value to a float. This can be done from an integer literal, a float literal, or a string literal (provided the string represents a float or an integer).

Casting to String

The str() function converts a value to a string. This can be done from strings, integer literals, float literals, and many other data types.

Practical Use Cases

When reading input from a user, it is often read as a string. You might need to convert it to another type for further processing.

 

user_input = input("Enter a number: ")
number = int(user_input)
print(f"The number you entered is {number}")

When dealing with numbers in string format, you need to convert them to the appropriate numeric type before performing calculations.

When you need to format numbers as strings for output purposes, you can use str().