Python Variables
Variables in Python
Introduction
Using variables in Python enhances its capabilities beyond being a simple calculator.
Variables offer numerous advantages over using raw numbers directly.
Creating Variables
Creating a variable in Python is straightforward.
Example:
python mv_population = 74728mv_populationis the variable name.The
=sign is the assignment operator.74728is the value assigned to the variable.
The assignment operator assigns the value on the right to the variable on the left.
The left side becomes a name for the value on the right side.
Variable Usage
Example:
python x = 2 y = x print(y)xis defined as2.yis defined as the value ofx(which is2).The value of
yis accessed using its name.
Variable Definition
Accessing an undefined variable results in an error.
Error message example:
NameError: name 'z' is not defined.
Multiple Assignments
Python allows assigning multiple variables simultaneously.
python x = 2 y = 3 z = 5Can be abbreviated as:
python x, y, z = 2, 3, 5Useful for assigning related variables like width, height, or coordinates.
Variable Naming
Descriptive variable names enhance code clarity.
Example:
python population_density = mountain_view_population / mountain_view_land_area
Naming Conventions and Restrictions
Allowed characters: letters, numbers, and underscores.
Cannot contain spaces.
Must start with a letter or underscore.
Avoid reserved words or built-in identifiers.
Using a reserved word as a variable name can cause errors or conflicts.
Pythonic naming convention: use lowercase letters and underscores to separate words.
Updating Variables
Variables can be updated by reassigning them.
Example:
python mv_population = 78128Updating based on changes:
python mv_population = mv_population + 4000 - 600In this line, the variable
mv_populationis being assigned to itself plus minus , resulting in .
Assignment Operators
Special assignment operators simplify increment and reassign operations.
Example:
python mv_population += 4000 # Incrementing mv_population by 4000+=operator increments the variable on the left by the value on the right.Other assignment operators:
-=,*=,/=, etc.These operators apply the arithmetic operation to the variable on the left with the value on the right.
Using assignment operators makes the code concise.