Glossary
HTML
CSS
JavaScript
Python
Alias
Booleans
Code block
Conditions
Console
Equality operator
False
Float
For loop
Formatted strings
Functions
Greater than operator
Greater than or equal to operator
If statement
Index
Inequality operator
Integer
Less than operator
Less than or equal to operator
Lists
Parameter
Return
String
The not operator
True
Variables
While loop
append()
insert()
pop()
PYTHON

Python Variables: Syntax, Usage, and Examples

Python variables are containers with names that store values like numbers, strings, and lists. In essence, variables make it easier to access and modify the values they store as a Python application runs.

How to Use Variables in Python

In Python, defining a variable is straightforward, and updating a variable works the same way. You simply assign a value to a variable name using the equals sign ( =). Here's a basic example:
# Defining or updating a variable
my_variable = value
  • my_variable: The name of the variable to create or update
  • =: The operator to assign a value to a variable
  • value: A value, such as a number, string, or list for the variable to store

    In Python, variables aren't declared like they are in many other programming languages. Instead, you create a variable right when you assign a value to it.

When to Use Variables in Python

Variables allow you to store and work with values like numbers, strings, and lists without tracking the values yourself. Instead, you only need to remember the variable names. Variables are essential for saving and updating information, from calculation results to user inputs.

Examples of Python Variables in Python

Variables make up virtually every Python application. Here are some simple examples:

User Input Storage

Variables are perfect for temporary data storage, i.e., storing information while a Python application runs. Consider a login form, which might store a username and password in variables.
username = input("Enter a username: ")
password = input("Enter a password: ")

Calculators

In applications with calculations, variables might be helpful to make such calculations easier to understand. For example, a salary calculator might store the individual components that make up a salary using variables.
base_salary = 50000
experience_multiplier = 1.3

salary = base_salary * experience_multiplier
print(salary)
Loop Control and Iteration
Variables are essential for controlling the flow of loops and their iterations. Consider iterating through a range from 0 to 10 as an example. A variable might store the value of the current element of the range.
for i in range(10): # the 'i' represents the current iteration
    print(i)
Conditional Logic
Variables can store the results of logical operations and conditions. Such results might be important for making decisions, like checking if a login attempt was successful.
login_successful = attempt_login(username, password)
if login_successful:
    print("Login succeeded.")
else:
    print("Login failed.")
Function Arguments and Return Values
When defining functions, variables pass information into the function as arguments. Functions can also return information through variables as return values.
def calculate_area(width, height): # 'width' and 'height' are variables
    return width * height
Managing State
In more complex Python applications, variables can be helpful for managing the state of an object. This is particularly useful in object-oriented programming, where instance variables store object state. As an example, consider a class for cars with make and model attributes.
class Car:
    def __init__(self, make, model):
        self.make = make # 'make' and 'model' are variables storing state
        self.model = model
Temporary Storage
During data processing, variables can serve as temporary storage for intermediate results. For example, think of swapping the values of two variables that track the height and width of an image. A temporary variable might help store the width value before the height value replaces it.
temp_variable = width # a variable to keep the value of width
width = height
height = temp_variable

Learn More About Variables in Python

Variable Names

A variable’s name identifies the variable and often indicates its purpose and the type of value it stores. Choosing meaningful and descriptive names helps in understanding Python code without needing excessive comments or documentation.


The Python programming language has some rules for naming variables:

1. Variable names must start with a letter (a-z, A-Z) or an underscore (_)
2. Variable names can contain letters, numbers, and underscores but cannot begin with a number
3. Avoid using any of Python's reserved keywords (e.g., forif, while, etc.) as variable names

Python variable names typically follow the “snake case” naming convention. Snake-case names start with a letter or underscore followed by letters, underscores, or numbers. As examples, consider base_salary and experience_multiplier.


In Python, variable names are case-sensitive, which means base_salary and BASE_SALARY are two different variable names. This feature allows for a flexible naming scheme but requires careful attention to avoid errors.

Variable Types

In Python, there are different types of variables, like integers, floats (floating-point numbers), strings, lists, and dictionaries. Each type has a specific purpose and operations it can handle. As opposed to many other programming languages, Python is dynamically typed. In Python, the variable type is determined at runtime based on the assigned value.

Consider a scenario where you're working with different variable types in a simple application. You might have an integer to store an age value, a float for a cash balance, and a string for a name. You might also use a list for favorite colors and a dictionary for a user profile:

age = 25 # Integer
balance = 100.50 # Float
name = "Alex" # String
favorite_colors = ["blue", "green", "red"] # List user_profile = {"username": "alex25", "active": True} # Dictionary
Type Conversions
Python also allows for type conversions, where you can explicitly change a variable from a certain type to another. Type conversions require type functions like int()float(), and str(). Converting types can be particularly useful for performing arithmetic operations on numbers input as strings. For example, converting a string to an integer: int("123") turns the string "123" into the integer 123.
number_string = input("Enter a number: ") # gets user input as string
number_int = int(number_string) # converts string to integer print(number_int + 1) ## adds 1 to the integer

Similarly, you might need to convert an integer to a string:

age = 30
age_string = str(age) # converts integer to string

Moreover, Python allows for implicit type conversion in certain operations to avoid type errors. For instance, adding an integer and a float creates a float value. Python implicitly converts the integer to a float to ensure the operation makes sense:

number_int = 5
number_float = 3.5
result = number_int + number_float # integer is implicitly converted to float

However, Python doesn’t implicitly convert between strings and other types to avoid errors and unexpected behavior. Instead, it requires type functions like int()float(), and str() to enable operating on variables of different types together. For instance, to concatenate a number with a string, you must explicitly convert the number to a string using str().

age = 30
greeting = "You are " + str(age) + " years old." print(greeting)

Variable Scope

Scope defines the part of a Python application within which a variable exists. Python organizes variables into various scopes. The most important scopes are local and global variables.

Local variables live within a function and are only accessible inside that function. They're not available outside the function, making them temporary and function-specific. Consider a variable inside a function that counts how often the function has been called. This variable will only be available for use within that function.

def print_local_var():
    local_var = 5 # Local variable, accessible only within 'function'
    print(local_var)

print_local_var() # This will print 5
# print(local_var) # This would raise an error because local_var is not accessible here

In Python, global variables are defined outside functions. Global variables are accessible throughout a program, including inside functions.

global_var = 10 # Global variable

def function():
    print(global_var) # Accessing global variable inside a function

function() # This will print 10
print(global_var) # This will also print 10
To modify a global variable inside a function, you need to declare it with global at the beginning of the function.
global_var = 10 # Global variable

def function():
    global global_var # Correct way to use the global statement
    global_var = 15 # Now modifying the global variable          print(global_var) # This will print 15

function() # This will print 15, because the function modifies the global variable
print(global_var) # This will also print 15, as the global variable has been modified

Consider a situation where you're tracking the progress of a task in a program. Creating a global variable at the start of your program allows you to update it throughout the program. This can be particularly useful in applications that need to maintain some configuration across various program parts.

Global variables in Python can make debugging and understanding your code more challenging, especially in larger programs. Therefore, keeping the use of global variables at a minimum is a good idea.

Constants

In Python, constants are variables meant to remain unchanged throughout the execution of a program. The naming convention of constants requires uppercase letters with underscores separating any words, such as BASE_SALARY or EXPERIENCE_MULTIPLIER.Typically, such constants are defined at the top of a Python file.

In reality, Python has no enforcement for constants. Constants are only meant to remain unchanged and can technically be changed at any time.

Learn to Code in Python for Free
Start learning now
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH