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 = 74728

    • mv_population is the variable name.

    • The = sign is the assignment operator.

    • 74728 is 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)

    • x is defined as 2.

    • y is defined as the value of x (which is 2).

    • The value of y is 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 = 5

  • Can be abbreviated as:
    python x, y, z = 2, 3, 5

  • Useful 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 = 78128

  • Updating based on changes:
    python mv_population = mv_population + 4000 - 600

  • In this line, the variable mv_population is being assigned to itself plus 4,0004,000 minus 600600, resulting in 78,12878,128.

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.