A guide on how to create and use variables in Python.
Variables are named locations that are used to store references to the object stored in memory.
When we create variables in Python, we must consider the following rules:
- A variable name must start with a letter or underscore
- A variable name cannot start with a number
- A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
- Variable names are case-sensitive (date, Date and DATE are three different variables)
- Variables can be of any length
- Variable names cannot be Python keywords
False class finally is return None continue for lambda try True def from nonlocal while and del global not with as elif if or yield pass else import assert break except in raise
Assigning Values to Variables
We use the assignment operator
= to assign value to a variable.
Example valid and invalid variable names and assignments:
#Legal variable names: name = "John" error_404 = 404 _status_200 = "OK" mySurname = "Doe" SURNAME = "Doe" surname2 = "Doe" #Illegal variable names: 200_OK = 200 error-500 = "Server Error" my var = "John" $myname = "John"
In Python, we can assign values to multiple variables in one line:
ok, redirect, server_error = 200, 300, 500 print(ok) print(redirect) print(server_error)
200 300 500
We can also assign the same value to multiple variables:
err_500 = err_501 = err_502 = "server_error" print(err_500) print(err_501) print(err_502)
Variables that are defined outside of a function are known as global variables.
Global variables can be used both inside and outside of functions.
status_ok = 200 def status_code(): print("Status code is ", status_ok) status_code()
If you create a variable with the same name inside a function, then the variable will be local to the function. The global variable will keep its value as when it was declared.
status = 200 def status_code(): status = 401 print("Status code is ", status) status_code() print("Status code is ", status)
Status code is 401 // first print statement Status code is 200 // second print statement
If you require to change the global variable’s value inside of a function, you have to use the
status = 200 def status_code(): global status status = 401 print("Status code is ", status) status_code() print("Status code is ", status)
Status code is 401 // first print statement Status code is 401 // second print statement