-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_data_types.py
More file actions
76 lines (62 loc) · 1.9 KB
/
Copy path02_data_types.py
File metadata and controls
76 lines (62 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
BUILT-IN DATA TYPES & DYNAMIC TYPING
====================================
Key Points:
- Python is dynamically typed (no need to declare variable types)
- Variables can change type at runtime
- Main types: int, float, str, bool, list, dict, tuple, set
"""
# Note: Variables can change type at runtime - no need to declare types
# DYNAMIC TYPING EXAMPLES
x = 42 # int
print(f"x = {x}, type: {type(x)}")
x = "forty-two" # now str
print(f"x = {x}, type: {type(x)}")
x = 3.14 # now float
print(f"x = {x}, type: {type(x)}")
x = True # now bool
print(f"x = {x}, type: {type(x)}")
print("\n=== BUILT-IN DATA TYPES ===")
# Note: Python has several built-in types - numbers, strings, booleans, and collections
# Numbers
integer_num = 100
float_num = 3.14159
complex_num = 3 + 4j
print(f"Integer: {integer_num}")
print(f"Float: {float_num}")
print(f"Complex: {complex_num}")
# Strings
text = "Python Programming"
multiline = """This is a
multiline string"""
print(f"String: {text}")
# Boolean
is_python_fun = True
is_difficult = False
print(f"Boolean: {is_python_fun}")
# Note: Collections can hold different data types and are very flexible
# Collections
my_list = [1, 2, 3, "mixed", True]
my_tuple = (1, 2, 3) # immutable
my_dict = {"name": "Alice", "age": 25}
my_set = {1, 2, 3, 3} # unique elements only
print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
print(f"Dictionary: {my_dict}")
print(f"Set: {my_set}")
# Note: Use isinstance() to check types safely - better than type() comparison
# TYPE CHECKING
def check_type(value):
if isinstance(value, int):
return "Integer"
elif isinstance(value, str):
return "String"
elif isinstance(value, list):
return "List"
else:
return "Other type"
# Test type checking
test_values = [42, "hello", [1, 2, 3], 3.14]
for val in test_values:
print(f"{val} is a {check_type(val)}")
print("\nData types mastered! ✓")