← Back to Chapters

Python Type Casting Exercises

? Python Type Casting Exercises

⚡ Quick Overview

Type casting in Python means converting a value from one data type to another, such as int to float, str to int, or numbers and collections to bool. Practicing these conversions helps you avoid type errors and write more flexible, reusable code.

Python mainly uses explicit casting via built-in functions like int(), float(), str(), bool(), list(), tuple(), and set().

? Key Concepts

  • Numeric casting: Convert between int and float.
  • String casting: Convert numeric strings like "20" to numbers.
  • Boolean casting: Use bool() to check truthiness of values.
  • Collection casting: Convert between list, tuple, and set.
  • Validity: Only valid numeric strings can be converted to numbers safely.

? Syntax and Theory

Common casting functions in Python:

  • int(x) – converts x to an integer (truncates decimals).
  • float(x) – converts x to a floating-point number.
  • str(x) – converts x to a string.
  • bool(x) – converts x to a Boolean (True or False).
  • list(x), tuple(x), set(x) – convert between collection types.

? Basic Type Conversion Example

This example shows how to convert between int, float, and str.

? View Code Example
x = 10      # int
y = 3.5     # float
z = "20"    # string

# int to float
print(float(x))   # 10.0

# float to int
print(int(y))     # 3

# string to int
print(int(z))     # 20

# int to string
print(str(x))     # "10"

? Converting with bool()

Use bool() to check whether values are considered “truthy” or “falsy”.

? View Code Example
print(bool(0))       # False
print(bool(10))      # True
print(bool(""))      # False
print(bool("Hello")) # True

In general, zero, empty strings, and empty collections are False. Most other values are True.

? Converting Collections

Python allows you to freely convert between lists, tuples, and sets using their constructors.

? View Code Example
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_set = set(my_list)

print(my_tuple)  # (1, 2, 3)
print(my_set)    # {1, 2, 3}

tuple() creates an immutable ordered sequence, while set() creates an unordered collection of unique elements.

? Live Output and Explanation

? What the Code Prints

  • Numeric casting example: float(10) becomes 10.0, and int(3.5) becomes 3 (decimal part discarded).
  • String to int: int("20") works because "20" is a valid numeric string.
  • Bool casting: bool(0) is False, but bool(10) is True. Similarly, bool("") is False and bool("Hello") is True.
  • Collections: tuple([1, 2, 3]) prints (1, 2, 3), and set([1, 2, 3]) prints something like {1, 2, 3} (order may vary).

? Exercise Templates with Type Casting

Use these small snippets as starting points for your own practice.

? View Exercise Template Code
# Convert a string input to integer and add 10
user_input = input("Enter a number: ")
num = int(user_input)
print(num + 10)

# Convert a float to integer and print
value = 7.9
print(int(value))

# Convert a list to tuple and set
items = [1, 2, 2, 3]
print(tuple(items))
print(set(items))

# Check truthiness of various values using bool()
print(bool([]))       # False
print(bool([1, 2]))   # True
print(bool(0.0))      # False
print(bool("Python")) # True

? Tips & Best Practices

  • Use int(), float(), str(), and bool() for basic conversions.
  • Collections like list, tuple, and set can be converted using their respective constructors.
  • Always ensure that string values are valid numbers before casting with int() or float().
  • Remember that int() on a float truncates the decimal part (it does not round).
  • Use bool() to quickly check whether inputs or collections are empty or non-empty.

? Try It Yourself

  • Ask the user for a number as a string, convert it to int, add 10, and print the result.
  • Store a floating-point number in a variable, convert it to int, and observe how the value changes.
  • Create a tuple, convert it to a list, append a new item, and print both versions.
  • Check the Boolean value of empty and non-empty collections like [], [0], (), (1,), {}, and {"key": "value"}.
  • Write a small script that reads three values as strings, casts them to appropriate types, and prints their sum or combined result.