Variables are containers for storing data values. In Python, a variable is created the moment you first assign a value to it.
1. Creating variables
Python has no command for declaring a variable (like var, let, or int in other languages).
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they have been set (since Python is dynamically typed).
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
2. Variable naming rules
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Python has specific rules for variable names:
- A variable name must start with a letter or the underscore character (
_). - 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 (
age,AgeandAGEare three different variables). - A variable name cannot be any of the Python keywords (like
if,for,while,class, etc.).
Examples of valid variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Examples of illegal variable names:
2myvar = "John" # Cannot start with a number
my-var = "John" # Hyphens are not allowed
my var = "John" # Spaces are not allowed
Best Practice: Use
snake_case(all lowercase words separated by underscores) for regular variable names in Python to maintain readability.
3. Assign multiple values
Python allows you to assign values to multiple variables in one line. This keeps your code concise.
Many Values to Multiple Variables
x, y, z = "Orange", "Banana", "Cherry"
print(x) # Orange
print(y) # Banana
print(z) # Cherry
Note: Make sure the number of variables matches the number of values, or else you will get an error.
One Value to Multiple Variables
You can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)
Unpacking a Collection
If you have a collection of values in a list or tuple, Python allows you to extract the values into variables. This is called unpacking.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x) # apple
4. Global vs local variables
The location where a variable is created determines its “scope” – where it can be accessed.
Local Variables
Variables created inside a function are known as local variables. They can only be used inside that specific function.
def myfunc():
x = "fantastic" # Local variable
print("Python is " + x)
myfunc()
# print(x) # This would cause an error because x is not defined outside the function
Global Variables
Variables created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
x = "awesome" # Global variable
def myfunc():
print("Python is " + x)
myfunc()
print("Python is really " + x)
If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was.
The global Keyword
Normally, when you create a variable inside a function, it is local. To create a global variable inside a function, or to change the value of a global variable inside a function, you can use the global keyword.
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x) # Will output "fantastic"
5. Constants (convention)
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later.
In Python, constants are usually declared and assigned on a module level. The convention is to use all capital letters with underscores separating words to signify that a variable should be treated as a constant.
Note: Python does not actually have built-in constant types. The uppercase naming is merely a convention to tell other programmers: “Do not change this value.”
PI = 3.14159
GRAVITY = 9.8
MAX_CONNECTIONS = 100
def calculate_area(radius):
# Using the constant
return PI * (radius ** 2)
Discussion
Loading comments...