Variables and Assignment

Why Variables

In Python, you can perform basic calculations by directly writing numbers and operations. Python will give you the results as output. For example:

3 + 5
# Output: 8

312 - 43
# Output: 269

7 * 2
# Output: 14

9 / 3
# Output: 3

You could write the numbers and operations every time and manually note down the results, but this can become cumbersome. Instead, you can save these values into variables to reuse them and make your code cleaner and more efficient.

sum = 3 + 5
sub = 312 - 43
mul = 7 * 2

Variables as Memory References

A variable stores values in memory.

A variable is a named storage location that holds data used during program execution. Variables allow you to store information that may change while the program runs.

Different Data Types

A variable can store different types of data:

city = "Marburg"  # String (Text)
temperature = 18.5  # Float (Decimal number)
cloud_coverage = 75  # Integer (Whole number)
is_sunny = False  # Boolean (True/False)

You can think of variables as references to stored information rather than fixed containers. When you assign a value to a variable, Python stores the value in memory, and the variable acts as a reference to that location.

Variable Reassignment

A variable can only refer to one value at a time. When a new value is assigned to the same variable, the previous reference is lost.

a = 5
print(a)  # Output: 5

a = 7
print(a)  # Output: 7

Naming Conventions

“All things are defined by names. Change the name, and you change the thing.” — Terry Pratchett, Pyramids

Rules for Variable Names:

  • Variables can contain letters, numbers, and underscores (_), but cannot start with a number.
  • No spaces or special characters are allowed (e.g., - is invalid).
  • Variable names are case-sensitive (myVar and myvar are different).
  • Reserved words like type or print should not be used as variable names.
  • Use underscores for multiple words:
flower_name = "Daisy"
print(flower_name)
  • Avoid starting with numbers:
3Beta = 4  # Invalid!
  • Use descriptive names instead of generic ones:
x1, xx  # Not recommended
num_students, avg_temperature  # Better!

Dynamic Typing

Python is dynamically typed, meaning the type of a variable is determined at runtime. You do not need to declare the type explicitly.

a = 1  # Integer
b = "Peter"  # String
c = [1, 2, 3]  # List
print(a + b + c)  # Causes an error!

Type Error

Python does not allow operations between incompatible types:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Updated: