Variables and Assignment in Python

 

Variables and Assignment in Python

What is a Variable?

  • A variable is a name that refers to a value stored in memory.
  • It acts as a reference, not a storage container.
  • Unlike other languages, Python variables do not store values but rather point to objects in memory.
  • Example:
x = 10 # x refers to an object holding the value 10

Variables Are Not Storage Containers

  • In Python, variables are like labels attached to objects in memory.
  • Assigning a variable does not copy data; it creates a reference.
  • Example:
a = [1, 2, 3] # a points to a list object
b = a # b refers to the same list, not a copy
  • Changing b affects a because both reference the same object.
b.append(4) # Modifies the list
print(a) # Output: [1, 2, 3, 4]

Variable Assignment in Python

  • The assignment operator (=) is used to bind variables to values.
  • Python allows multiple assignments in a single statement.
  • Example:
a, b, c = 5, 10, 15
name = "Alice"

Multiple Assignment in Python

  • Python allows assigning multiple values to multiple variables in one line.
  • This feature makes code more concise and readable.
x, y, z = 1, 2, 3 # Assigning different values
a = b = c = 100 # Assigning the same value to multiple variables
  • Swapping values using multiple assignment:
a, b = b, a # Swap values of a and b

Dynamic Typing in Python

  • Python is dynamically typed.
  • The type of a variable is determined at runtime.
  • You can reassign a variable to a different type.
x = 5 # Integer
x = "Hello" # Now a string

Best Practices for Variable Naming

  • Use meaningful variable names.
  • Follow the PEP 8 naming conventions.
  • Avoid using Python keywords as variable names.
  • Example of valid names:
student_name = "John"
total_marks = 95

Video

PDF

Variables and Assignment in Python

Summary

  • Variables in Python are references, not storage containers.
  • The assignment operator = creates a reference.
  • Python supports multiple assignments.
  • Python supports dynamic typing.
  • Follow best practices for variable naming.

Thank You!

 

©Postnetwork-All rights reserved.