Fundamentals of Python: Variables

Table of ContentsPart One: Basic Concepts of Variables

  1. What is a Variable

  2. Variable Naming Rules

  3. Basic Data Types

  4. Variable Assignment and Reassignment

Part Two: In-Depth Data Types

  1. Numeric Types (Integer, Float, Complex)

  2. String Types

  3. Boolean Types

  4. Type Conversion

Part Three: Advanced Variable Concepts

  1. Concept of Constants

  2. Multiple Assignments

  3. Variable Scope

  4. Basics of Memory Management

Detailed Course Content

Part One: Basic Concepts of Variables

1.1 What is a Variable

# Example 1: Basic Variable Assignment
# A variable is like a label that points to data stored in memory

# Assign the number 10 to the variable age
age = 10
print(age)  # Output: 10

# Assign the string "Alice" to the variable name
name = "Alice"
print(name)  # Output: Alice

# Variables can be reassigned
age = 25  # Now the value of age is 25
print(age)  # Output: 25

1.2 Variable Naming Rules

# Example 2: Valid Variable Naming
student_name = "Zhang San"  # Use underscores to separate words
studentAge = 20       # Camel case
_count = 5            # Starts with an underscore (usually has special meaning)
MAX_SIZE = 100        # All uppercase usually indicates a constant

# Example 3: Invalid Variable Naming (uncommenting will cause an error)
# 2name = "Li Si"      # Cannot start with a number
# my-name = "Wang Wu"  # Cannot contain hyphens
# class = "Math"      # Cannot use keywords

# View Python keywords
import keyword
print(keyword.kwlist)  # Display all Python keywords

1.3 Basic Data Types

# Example 4: Basic Data Types Demonstration
# Integer (int)
age = 25
print(type(age))  # Output: <class 'int'>

# Float (float)
height = 1.75
print(type(height))  # Output: <class 'float'>

# String (str)
name = "Python Learner"
print(type(name))  # Output: <class 'str'>

# Boolean (bool)
is_student = True
print(type(is_student))  # Output: <class 'bool'>

1.4 Variable Assignment and Reassignment

# Example 5: Dynamic Nature of Variables
# Python is a dynamically typed language, variable types can change
x = 10
print(f"x's value: {x}, type: {type(x)}")  # Output: x's value: 10, type: <class 'int'>

x = "Now I am a string"
print(f"x's value: {x}, type: {type(x)}")  # Output: x's value: Now I am a string, type: <class 'str'>

# Multiple assignments
a, b, c = 1, 2, 3
print(a, b, c)  # Output: 1 2 3

# Chained assignment
x = y = z = 100
print(x, y, z)  # Output: 100 100 100

Part Two: In-Depth Data Types

2.1 Numeric Type Operations

# Example 6: Numeric Operations
# Basic arithmetic operations
a = 10
b = 3

print("Addition:", a+b)    # Output: 13
print("Subtraction:", a-b)    # Output: 7
print("Multiplication:", a*b)    # Output: 30
print("Division:", a/b)    # Output: 3.333...
print("Floor Division:", a//b)   # Output: 3
print("Modulus:", a%b)    # Output: 1
print("Exponentiation:", a**b) # Output: 1000

# Floating point precision issue
print(0.1+0.2)  # Output: 0.30000000000000004
# This is due to the way floating point numbers are represented in computers

# Use decimal module for precise calculations
from decimal import Decimal
result = Decimal('0.1') + Decimal('0.2')
print(result)  # Output: 0.3

2.2 String Operations

# Example 7: String Operations
# String concatenation
first_name = "Zhang"
last_name = "San"
full_name = first_name + last_name
print(full_name)  # Output: ZhangSan

# String repetition
laugh = "Ha" * 3
print(laugh)  # Output: Hahaha

# String indexing and slicing
text = "Python Programming"
print(text[0])     # Output: P (first character)
print(text[-1])    # Output: ing (last character)
print(text[0:6])   # Output: Python (slicing)
print(text[6:])    # Output: Programming

# String methods
message = "  Hello, World!  "
print(message.strip())        # Remove leading and trailing spaces: "Hello, World!"
print(message.upper())        # Convert to uppercase: "  HELLO, WORLD!  "
print(message.lower())        # Convert to lowercase: "  hello, world!  "
print(message.replace("World", "Python"))  # Replace: "  Hello, Python!  "

2.3 Boolean Types and Logical Operations

# Example 8: Boolean Operations
# Comparison operators
a = 10
b = 20

print(a == b)  # Equal: False
print(a != b)  # Not equal: True
print(a > b)   # Greater than: False
print(a < b)   # Less than: True
print(a >= b)  # Greater than or equal: False
print(a <= b)  # Less than or equal: True

# Logical operators
x = True
y = False

print(x and y)  # AND operation: False (only returns True if both are True)
print(x or y)   # OR operation: True (returns True if at least one is True)
print(not x)    # NOT operation: False (negation)

# Practical application
age = 18
has_id = True
can_enter = age >= 18 and has_id
print(f"Can enter: {can_enter}")  # Output: Can enter: True

2.4 Type Conversion

# Example 9: Type Conversion
# Explicit type conversion
num_str = "123"
num_int = int(num_str)    # Convert string to integer
print(num_int, type(num_int))  # Output: 123 &lt;class 'int'&gt;

num_float = float("3.14")  # Convert string to float
print(num_float, type(num_float))  # Output: 3.14 &lt;class 'float'&gt;

str_num = str(456)       # Convert number to string
print(str_num, type(str_num))  # Output: 456 &lt;class 'str'&gt;

# Implicit type conversion
result = 10 + 3.14      # Integer + Float = Float
print(result, type(result))  # Output: 13.14 &lt;class 'float'&gt;

# Boolean values in operations
true_value = True       # True is equivalent to 1
false_value = False     # False is equivalent to 0
print(10 + true_value)  # Output: 11
print(10 + false_value) # Output: 10

# Conversion caution
try:
    invalid = int("abc")  # This will raise an error
except ValueError as e:
    print(f"Conversion error: {e}")

Part Three: Advanced Variable Concepts

3.1 Concept of Constants

# Example 10: Constant Conventions
# Python does not have true constants, but it is convention to use all uppercase for constants
MAX_CONNECTIONS = 100
PI = 3.14159
DATABASE_URL = "mysql://localhost:3306/mydb"

# Attempt to "change" a constant (technically possible, but not recommended)
print(f"Max connections: {MAX_CONNECTIONS}")
MAX_CONNECTIONS = 200  # Technically feasible, but not in accordance with convention
print(f"Modified max connections: {MAX_CONNECTIONS}")

# Use enumeration to define related constants
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)    # Output: Color.RED
print(Color.RED.value)  # Output: 1

3.2 Multiple Assignments and Swapping

# Example 11: Advanced Assignment Techniques
# Tuple unpacking
coordinates = (10, 20, 30)
x, y, z = coordinates
print(f"x: {x}, y: {y}, z: {z}")  # Output: x: 10, y: 20, z: 30

# List unpacking
colors = ["Red", "Green", "Blue"]
r, g, b = colors
print(f"RGB: {r}{g}{b}")  # Output: RGB: RedGreenBlue

# Use * to collect excess values
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print(f"First: {first}, Middle: {middle}, Last: {last}")
# Output: First: 1, Middle: [2, 3, 4], Last: 5

# Swap two variable values (no temporary variable needed)
a = 10
b = 20
print(f"Before swap: a={a}, b={b}")  # Output: Before swap: a=10, b=20

a, b = b, a  # Swap values
print(f"After swap: a={a}, b={b}")  # Output: After swap: a=20, b=10

3.3 Variable Scope (This section can be revisited after learning functions)

# Example 12: Variable Scope
# Global variable
global_var = "I am a global variable"

def test_function():
    # Local variable
    local_var = "I am a local variable"
    print(f"Accessing global variable inside function: {global_var}")
    print(f"Accessing local variable inside function: {local_var}")
    
    # To modify a global variable, use the global keyword
    global global_var
    global_var = "Modified global variable"

test_function()
print(f"Accessing global variable outside function: {global_var}")

# Attempting to access local variable will raise an error
try:
    print(local_var)  # This will raise an error, as local_var is a local variable
except NameError as e:
    print(f"Error: {e}")

# Scope of nested functions
def outer_function():
    outer_var = "Outer variable"
    
    def inner_function():
        nonlocal outer_var  # Use nonlocal to modify the variable from the outer function
        outer_var = "Modified outer variable"
        inner_var = "Inner variable"
        print(f"Inner function: {outer_var}")
    
    inner_function()
    print(f"Outer function: {outer_var}")
    # print(inner_var)  # This will raise an error, inner_var is defined in the inner function

outer_function()

3.4 Memory Management

# Example 13: Variables and Memory
# The id() function returns the memory address of an object
a = 10
b = 10
print(f"a's id: {id(a)}")
print(f"b's id: {id(b)}")  # Small integers are cached, id may be the same

# Difference between is and ==
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1

print(f"list1 == list2: {list1 == list2}")  # True, values are equal
print(f"list1 is list2: {list1 is list2}")  # False, not the same object
print(f"list1 is list3: {list1 is list3}")  # True, is the same object

# Reference counting
import sys

x = [1, 2, 3]
print(f"x's reference count: {sys.getrefcount(x)}")  # Note: getrefcount itself increases a temporary reference

# Assigning y to x
y = x
print(f"Reference count of x after assignment: {sys.getrefcount(x)}")

del y
print(f"Reference count of x after deleting y: {sys.getrefcount(x)}")

This course system covers all important concepts of Python variables, helping everyone establish a solid programming foundation through rich code examples.

Leave a Comment