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, -10float– decimal numbers like 3.14str– strings like "hello"bool– Boolean True/Falselist,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 integerfloat()– convert to floating-pointstr()– convert to stringbool()– convert to Booleanlist(), 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()withrepr()in formatting (optional advanced)
๐ก Try It Yourself
- Ask user input for a number (string) and convert it to int to add 10.
- Check the type of the result using
type(). - Convert a list to a tuple and a tuple to a list, then print both.
- Convert a number to boolean and see the result for 0 and 5.
- Try converting a non-numeric string to int and observe the error.
No comments:
Post a Comment