๐ Related code file:
02_data_types.py
Every value in Python has a type that determines what you can do with it. Python is dynamically typed, meaning you don't declare types explicitly โ Python figures them out automatically, and a variable can even change type during a program's life.
In statically typed languages (like Java or C++), you must declare a variable's type. In Python, you just assign a value:
x = 42 # x is an int
x = "forty-two" # now x is a str
x = 3.14 # now x is a float
x = True # now x is a boolThe type belongs to the value, not the variable. Use type() to check:
print(type(42)) # <class 'int'>
print(type("hello")) # <class 'str'>
print(type(3.14)) # <class 'float'>integer_num = 100 # int โ whole numbers
float_num = 3.14159 # float โ decimal numbers
complex_num = 3 + 4j # complex โ real + imaginarytext = "Python Programming"
multiline = """This is a
multiline string"""is_python_fun = True
is_difficult = False| Type | Syntax | Ordered? | Mutable? | Duplicates? |
|---|---|---|---|---|
list |
[1, 2, 3] |
โ | โ | โ |
tuple |
(1, 2, 3) |
โ | โ | โ |
dict |
{"a": 1} |
โ * | โ | Keys unique |
set |
{1, 2, 3} |
โ | โ | โ |
my_list = [1, 2, 3, "mixed", True] # ordered, changeable
my_tuple = (1, 2, 3) # ordered, unchangeable
my_dict = {"name": "Alice", "age": 25} # key-value pairs
my_set = {1, 2, 3, 3} # unique elements โ {1, 2, 3}*Dictionaries preserve insertion order since Python 3.7.
value = 42
if isinstance(value, int):
print("It's an integer")
isinstance()is preferred overtype(value) == intbecause it also handles subclasses correctly.
int("123") # 123 (str โ int)
str(123) # "123" (int โ str)
float("3.14") # 3.14 (str โ float)
list("abc") # ['a', 'b', 'c']
bool(0) # False
bool(1) # Trueโ Mixing incompatible types:
"Age: " + 25 # TypeError: can only concatenate str to str
# Fix:
"Age: " + str(25) # "Age: 25"โ Assuming int division gives an int:
10 / 3 # 3.333... (always a float with /)
10 // 3 # 3 (use // for integer division)โ Confusing type() comparison with isinstance():
type(True) == int # False
isinstance(True, int) # True (bool is a subclass of int!)โ
Use isinstance() for type checks.
โ
Convert input explicitly โ input() always returns a string.
โ
Use tuples for fixed collections, lists for changeable ones.
โ
Use descriptive variable names that hint at the type (names_list, age_count).
-
Predict the type: What does
type(3 / 1)return? Verify by running it. -
Convert and calculate: The variable
age = "30"is a string. Convert it to an integer and add 5. -
Build a collection: Create a dictionary representing a book with keys
title,author, andyear. Print each value with its type. -
Deduplicate: Given
nums = [1, 2, 2, 3, 3, 3], use asetto find the unique values.
๐ก Solution hints
# Exercise 2
age = "30"
print(int(age) + 5) # 35
# Exercise 4
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums) # {1, 2, 3}- Python is dynamically typed โ no need to declare types.
- Core types:
int,float,str,bool,list,tuple,dict,set. - Use
type()to inspect andisinstance()to check types. - Convert between types with
int(),str(),float(),list(), etc.
python basic/02_data_types.py
โฎ๏ธ Previous: Syntax & Indentation | โญ๏ธ Next: Operators โ