Python Casting

Casting is the process of converting a variable from one data type to another. In Python, you can cast between different data types using built-in functions. This is particularly useful when you need to perform operations that require a specific data type.

Tutorials dojo strip

Casting Functions

Python provides several built-in functions for casting between data types:

  1. int() – Converts a value to an integer.
  2. float() – Converts a value to a floating-point number.
  3. str() – Converts a value to a string.

Converting to Integer

Use the int() function to convert a value to an integer. This function can handle strings representing whole numbers, floating-point numbers (by truncating the decimal part), and boolean values.

In the example below, the int() function is used to convert a string "10" to an integer 10, a float 3.14 to an integer 3, and a boolean True to an integer 1.

Python

Converting to Float

Use the float() function to convert a value to a floating-point number. This function can handle strings representing numbers and integer values.

In the example above, the float() function is used to convert a string "3.14" to a float 3.14 and an integer 10 to a float 10.0.

Python

Converting to String

Use the str() function to convert a value to a string. This function can handle numbers, booleans, and other data types.

In the example above, the str() function is used to convert an integer 10 to a string "10", a float 3.14 to a string "3.14", and a boolean False to a string "False".

Python

Python Casting Example Code

This program uses a predefined input value instead of prompting the user. The input, which is a string, is converted to a float using the float() function. The program performs addition and multiplication operations and prints the results. Finally, the results are converted to strings and printed again.

Python




Python Labs

Tutorials dojo strip