Variables

A variable is used to store data that will be used by the program. This data can be a number, a string, a Boolean, a list or some other data type. Every variable has a name which can consist of letters, numbers, and the underscore character _.

The equal sign = is used to assign a value to a variable. After the initial assignment is made, the value of a variable can be updated to new values as needed.

# These are all valid variable names and assignment
user_name = "@sonnynomnom"
user_id = 100
new_user = False

# A variable's value can be changed after assignment
points = 100
points = 120

Plus Equals

Python offers a shorthand for updating variables. When you have a number saved in a variable and want to add to the current value of the variable, you can use the += (plus-equals) operator.

# First we have a variable with a number saved
number_of_miles_hiked = 12

# Then we need to update that variable
# Let's say we hike another two miles today
number_of_miles_hiked += 2

# The new value is the old value
# Plus the number after the plus-equals
print(number_of_miles_hiked)
# Prints 14

The plus-equals operator also can be used for string concatenation, like so:

hike_caption = "What an amazing time to walk through nature!"

# Almost forgot the hashtags!
hike_caption += " #nofilter"
hike_caption += " #blessed"

The += operator allows adding more than just a single value at a time. Anything on the right-hand side of the += will be evaluated, and then it will be added to the variable which is then updated to that new value.

# Plus Equals with a single value:
miles = 80
miles += 20 # miles is now 100

# Plus Equals with more than one value:
snow_level = 10
snow_level += 20 + 10 + 40 # snow_level is now 80

The Scope of Variables

In Python, a variable defined inside a function is called a local variable. It cannot be used outside of the scope of the function, and attempting to do so without defining the variable outside of the function will cause an error.

A variable that is defined outside of a function is called a global variable. It can be accessed inside the body of a function.

a = 5

def f1():
  a = 2
  print(a)
  
print(a)   # Will print 5
f1()       # Will print 2

In the example, the variable a is defined both inside and outside of the function. When the function f1() is implemented, a is printed as 2 because it is locally defined to be so. However, when printing a outside of the function, a is printed as 5 because it is implemented outside of the scope of the function.

Last updated

Was this helpful?