Back to course

Type Conversion (Casting) between Basic Types

Python Programming: The 0 to Hero Bootcamp

Type Casting

Sometimes you need to convert a value from one data type to another (e.g., converting a string that looks like a number into an actual number so you can perform math).

Python provides built-in functions for casting:

  • int()
  • float()
  • str()
  • bool()

Converting to Integer (int())

python float_val = 10.99 int_val = int(float_val) # Decimals are truncated (cut off, not rounded) print(int_val) # Output: 10

string_num = '123' actual_num = int(string_num) print(actual_num * 2) # Output: 246

Converting to Float (float())

python integer_val = 5 float_val = float(integer_val) print(float_val) # Output: 5.0

Converting to String (str())

python score = 95 message = 'Your score is ' + str(score) # Concatenating number and string requires casting print(message) # Output: Your score is 95