AITC Wiki

Python Variables

Python 变量

Python Variables

中文版:Python 变量

A variable is a name that refers to a value stored in memory, created through assignment and governed by dynamic typing.

Definition

A variable in Python is like a named box in the computer’s memory. Inside the box, there is a pointer to the current value for that variable. A variable is created with an assignment statement (=), with the variable’s name on the left and the value it should store on the right.

x = 42
hours = 35.0
rate = 12.50
pay = hours * rate

Dynamic Typing

Python uses dynamic typing: the data type of a variable is determined automatically at runtime, rather than being explicitly declared in advance. The interpreter infers the type based on the value assigned, and variables can be reassigned to values of different types freely.

x = 42          # x is an integer
x = "First year" # Now x is a string

Runtime type checking catches incompatible operations during execution:

x = 5
y = "text"
print(x + y)  # Error: unsupported operand type(s) for +: 'int' and 'str'

Naming Rules

  • Must start with a letter or underscore _
  • Case sensitive (spam, Spam, and SPAM are different variables)
  • Cannot use reserved words as identifiers

Valid names: spam, eggs, spam23, _speed
Invalid names: 23spam, #sign, var.12

Reserved Words

False    class    return   is       finally
None     if       for      lambda   continue
True     def      from     while    nonlocal
and      del      global   not      with
as       elif     try      or       yield
assert   else     import   pass
break    except   in       raise

Common Misconceptions

  • Confusing assignment with equality: = assigns a value; == compares for equality.
  • Reusing variable names for different types: While Python allows this, it can make code harder to read and debug.

Sources