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.
Variables do not need to be declared with any particular type and can even change type after they have been set.
Variable Names (Rules)
A variable can have a short name (like x) or a more descriptive name (age, total_price). Rules:
- Must start with a letter or underscore
_ - Cannot start with a number
- Can only contain letters, numbers, and underscores (A–Z, 0–9, _)
- Variable names are case-sensitive (
age,AgeandAGEare different)
Assign Multiple Values
Python allows you to assign values to multiple variables in one line:
You can also assign the same value to multiple variables:
Output Variables
Use the print() function to output variables. You can combine text and variables using + or an f-string (recommended):
Global Variables
Variables created outside of a function are called global variables and can be used by everyone, both inside and outside of functions.
user_name, total_price, is_active. This is the Python convention (PEP 8).