← Python EnglishChapter 02 of 13

Variables and Data Types

## Learning Objectives - Understand Python's dynamic typing - Master basic data types - Learn type conversion - Work with type checking ## Variables ### Creating Variables ```python x = 5 # Integer name = "Alice" # String pi = 3.14 # Float is_active = True # Boolean ``` ### Dynamic Typing Python variables can change type: ```python x = 5 # int x = "hello" # Now it's a str x = 3.14 # Now it's a float ``` ## Basic Data Types ### Integers (int) ```python age = 25 negative = -10 large_number = 1_000_000 # Underscore for readability binary = 0b1010 # 10 in binary hexadecimal = 0xFF # 255 in hex octal = 0o77 # 63 in octal ``` ### Floats (float) ```python pi = 3.14159 scientific = 1.5e10 # 1.5 * 10^10 negative = -0.5 ``` ### Strings (str) ```python name = "Alice" greeting = 'Hello' multi_line = """ This is a multi-line string """ raw = r"C:\Users\Name" # Raw string (no escape chars) ``` ### Booleans (bool) ```python is_active = True is_valid = False ``` ### None Type ```python result = None ``` ## Type Checking ### type() Function ```python x = 5 print(type(x)) # name = "Alice" print(type(name)) # ``` ### isinstance() ```python x = 5 print(isinstance(x, int)) # True print(isinstance(x, str)) # False print(isinstance(x, (int, float))) # True (int or float) ``` ## Type Conversion ### Explicit Conversion ```python # int to float x = 5 print(float(x)) # 5.0 # float to int (truncates) y = 3.7 print(int(y)) # 3 (not 4!) # to string x = 5 print(str(x)) # "5" # string to int/float num = "42" print(int(num)) # 42 print(float(num)) # 42.0 ``` ### String to List ```python text = "hello" print(list(text)) # ['h', 'e', 'l', 'l', 'o'] ``` ### List to String ```python chars = ['h', 'e', 'l', 'l', 'o'] print("".join(chars)) # "hello" ``` ## String Formatting ### f-strings (Python 3.6+) ```python name = "Alice" age = 30 print(f"My name is {name} and I'm {age}") print(f"In 5 years: {age + 5}") print(f"Pi: {3.14159:.2f}") # 3.14 ``` ### format() Method ```python name = "Alice" print("Hello, {}".format(name)) print("{1} and {0}".format("Bob", "Alice")) print("{name} is {age}".format(name="Alice", age=30)) ``` ### % Operator ```python name = "Alice" print("Hello, %s" % name) print("%s is %d years old" % (name, 30)) ``` ## Mutable vs Immutable ### Immutable Types - int, float, str, tuple, frozenset ```python # Strings are immutable s = "hello" # s[0] = "H" # Error! s = "Hello" # Creates new string # Tuples are immutable t = (1, 2, 3) # t[0] = 4 # Error! ``` ### Mutable Types - list, dict, set ```python # Lists are mutable nums = [1, 2, 3] nums[0] = 10 # OK nums.append(4) # OK # Dictionaries are mutable d = {"a": 1} d["b"] = 2 # OK ``` ## Variable Naming ### Rules - Start with letter or underscore - Can contain letters, numbers, underscores - Case-sensitive ```python valid_name = "ok" _private = "hidden" camelCase = "not preferred in Python" CONSTANT = "use UPPER_CASE" ``` ### Reserved Words ```python # Don't use these as variable names # False, None, True, and, as, assert, async, await, # break, class, continue, def, del, elif, else, except, # finally, for, from, global, if, import, in, is, # lambda, nonlocal, not, or, pass, raise, return, try, # while, with, yield ``` ## Multiple Assignment ```python x, y, z = 1, 2, 3 a = b = c = 0 # All equal 0 ``` ## Swapping Variables ```python a, b = 1, 2 a, b = b, a # Simple swap print(a, b) # 2, 1 ``` ## Summary - Python uses dynamic typing - Basic types: int, float, str, bool, None - Use `type()` and `isinstance()` to check types - Convert types with `int()`, `float()`, `str()`, etc. - Strings are immutable; lists and dicts are mutable - Use f-strings for string formatting - Variable names: letters, numbers, underscores; case-sensitive

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →