▶ Try It Yourself

Python Variables

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Example
x = 5 y = "Hello, World!" 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.

Example — Changing type
x = 4 # x is an integer x = "Sally" # x is now a string print(x)

Variable Names (Rules)

A variable can have a short name (like x) or a more descriptive name (age, total_price). Rules:

Example — Legal variable names
myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John"

Assign Multiple Values

Python allows you to assign values to multiple variables in one line:

Example — Many values to many variables
x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z)

You can also assign the same value to multiple variables:

Example — One value to many variables
x = y = z = "Orange" print(x) print(y) print(z)

Output Variables

Use the print() function to output variables. You can combine text and variables using + or an f-string (recommended):

Example — f-strings (modern way)
name = "Alice" age = 25 print(f"My name is {name} and I am {age} years old.")

Global Variables

Variables created outside of a function are called global variables and can be used by everyone, both inside and outside of functions.

Example — Global vs Local
x = "awesome" # global variable def my_function(): print("Python is " + x) my_function() print("Python is " + x)
✅ Best Practice Use snake_case for variable names: user_name, total_price, is_active. This is the Python convention (PEP 8).