Monday, August 25, 2025

๐ŸTYPE CHECKING AND CONVERSIONS IN PYTHON

Python variables have types, and sometimes you need to check or convert them to another type for proper operations.

What is a Type?

Every value in Python belongs to a type (also called a class). The type determines what operations are allowed. Common types include:

  • int – integers like 5, -10
  • float – decimal numbers like 3.14
  • str – strings like "hello"
  • bool – Boolean True/False
  • list, tuple, set, dict – containers

Checking the Type of a Variable


x = 42
y = 3.14
z = "Python"
flag = True

print(type(x))      # <class 'int'>
print(type(y))      # <class 'float'>
print(type(z))      # <class 'str'>
print(type(flag))   # <class 'bool'>

# Check type using isinstance()
print(isinstance(x, int))    # True
print(isinstance(y, int))    # False

Tip: isinstance() is preferred when checking types for conditional logic.

Converting Between Types

Python allows converting values from one type to another using built-in functions:

  • int() – convert to integer
  • float() – convert to floating-point
  • str() – convert to string
  • bool() – convert to Boolean
  • list(), tuple(), set(), dict() – convert to containers

num_str = "100"
num_int = int(num_str)     # 100
num_float = float(num_str) # 100.0

print(num_int + 50)        # 150
print(num_float + 0.5)     # 100.5

# Converting containers
letters = "abc"
letters_list = list(letters)   # ['a','b','c']
letters_tuple = tuple(letters) # ('a','b','c')
letters_set = set(letters)     # {'a','b','c'}

Common Mistakes

  • Converting non-numeric string to int/float: int("abc") → ValueError
  • Converting float string with decimal using int: int("3.14") → ValueError
  • Passing wrong type to container conversion: list(123) → TypeError (123 is not iterable)
  • Confusing str() with repr() in formatting (optional advanced)

๐Ÿ’ก Try It Yourself

  1. Ask user input for a number (string) and convert it to int to add 10.
  2. Check the type of the result using type().
  3. Convert a list to a tuple and a tuple to a list, then print both.
  4. Convert a number to boolean and see the result for 0 and 5.
  5. Try converting a non-numeric string to int and observe the error.

๐Ÿ–ฅ️ Practice in Browser

No comments:

Post a Comment

๐ŸWhat is scikitlearn??