Python Variables
Variables
A variable in Python is used to store information that can be reused later in a program. You can think of a variable as a label attached to a value, which lets you refer to that value by name instead of repeating it.
Variables are used in almost every line of a real program: to store user input, keep a running total, hold data loaded from a file, or remember the result of a calculation.
Creating Variables
Python has no special keyword for declaring variables (unlike int x; in C or let x in JavaScript). A variable is created automatically the first time you assign a value to it using the assignment operator =.
Syntax
variable_name = value
The = sign means "assign the value on the right to the name on the left." It does not mean "is equal to" as in mathematics.
Example
count = 12
username = "Alice"
print(count)
print(username)
Expected output:
12
Alice
Explanation:
count = 12creates a variable namedcountthat refers to the integer12.username = "Alice"creates a variable namedusernamethat refers to the string"Alice".print()displays the value each variable refers to.
Python Determines the Type Automatically
You never state a variable's type. Python determines the type from the value you assign. This is called dynamic typing.
A variable can even refer to a value of a different type later:
data = 10 # data refers to an integer
print(data)
data = "ten" # now data refers to a string
print(data)
Expected output:
10
ten
Variables Can Be Updated
Assigning a new value to an existing variable replaces the old value:
score = 50
score = score + 10
print(score)
Expected output:
60
Python first evaluates the right side (50 + 10) and then assigns the result back to score.
Type Casting
Sometimes you need to convert a value from one data type to another — for example, turning the text "20" into the number 20 so you can perform calculations with it. This explicit conversion is called type casting.
Python provides built-in functions for this:
| Function | Converts to | Example | Result |
|---|---|---|---|
str() | String | str(45) | '45' |
int() | Integer | int("20") | 20 |
float() | Floating-point number | float(8) | 8.0 |
Example
num_text = str(45) # Converts a number to a string
num_value = int("20") # Converts a string to an integer
decimal = float(8) # Converts an integer to a float
print(num_text, num_value, decimal)
Expected output:
45 20 8.0
Casting is especially useful when working with user input, because input() always returns text — even if the user types a number. You will learn more in the Python Type Casting lesson.
Checking the Data Type
You can find out the type of any value or variable using the built-in type() function.
Example
price = 99.99
status = "Available"
quantity = 3
print(type(price))
print(type(status))
print(type(quantity))
Expected output:
<class 'float'>
<class 'str'>
<class 'int'>
Checking types is helpful for debugging and for understanding how your program is handling data.
Using Single or Double Quotes
String values can be written with single quotes (' ') or double quotes (" "). Both create exactly the same kind of string.
city = "Chennai"
language = 'Python'
print(city)
print(language)
Expected output:
Chennai
Python
Choose one style and use it consistently in your code.
Case Sensitivity in Variable Names
Python treats uppercase and lowercase letters as different characters. Variable names that differ only in letter case are separate variables.
score = 85
Score = "Excellent"
print(score)
print(Score)
Expected output:
85
Excellent
score and Score are two distinct variables, and changing one does not affect the other. In practice, avoid names that differ only by case, because they are easy to confuse.
Naming Variables
Variable names can be very short (such as i or n) or descriptive (such as student_age, total_marks, or file_count). Short names are acceptable for simple loop counters, but descriptive names make code much easier to understand and maintain.
# Hard to understand
x = 450
y = 3
z = x * y
# Easy to understand
price_per_item = 450
quantity = 3
total_price = price_per_item * quantity
Rules for Valid Variable Names
Python enforces these rules strictly:
- A variable name must begin with a letter (
a–z,A–Z) or an underscore (_). - It cannot start with a number.
- It can contain only letters, numbers, and underscores.
- Variable names are case-sensitive (
age,Age, andAGEare different). - Python keywords (such as
for,if,class,True,None) cannot be used as variable names.
Examples of Valid Variable Names
user = "Ravi"
user_name = "Ravi"
_user_id = 101
userName = "Ravi"
USERNAME = "Ravi"
user2 = "Ravi"
All of these follow Python's naming rules.
Examples of Invalid Variable Names
3user = "Ravi" # Cannot start with a number
user-name = "Ravi" # Hyphens are not allowed
user name = "Ravi" # Spaces are not allowed
class = "Ravi" # 'class' is a reserved keyword
Each of these lines raises a SyntaxError.
Why are hyphens not allowed? Python reads
user-nameasuserminusname, which is a subtraction, not a name.
Avoid Shadowing Built-in Names
Names such as print, list, str, input, and type are not keywords, so Python allows you to use them as variable names. However, doing so replaces the built-in function in that part of your program:
list = [1, 2, 3]
# list("abc") would now fail, because 'list' no longer refers to the built-in
Choose names like numbers or items instead.
Naming Variables With Multiple Words
When a variable name contains more than one word, format it so the words are easy to read. Three styles are common:
Camel Case
The first word starts with a lowercase letter, and each following word starts with an uppercase letter.
totalPriceAmount = 2500
Pascal Case
Every word starts with an uppercase letter.
TotalPriceAmount = 2500
Snake Case
All words are lowercase and separated by underscores.
total_price_amount = 2500
Snake case is the recommended style for variable and function names in Python, as defined by PEP 8, Python's official style guide. Pascal case is used for class names (for example, StudentRecord), and all-uppercase snake case is used for constants (for example, MAX_USERS = 100).
| Style | Example | Typical Use in Python |
|---|---|---|
| snake_case | total_price | Variables and functions |
| PascalCase | TotalPrice | Class names |
| UPPER_SNAKE_CASE | TOTAL_PRICE | Constants |
| camelCase | totalPrice | Rare in Python; common in JavaScript and Java |
Assigning Multiple Values to Multiple Variables
Python can assign several values to several variables in a single statement. Each variable receives the value in the matching position.
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
Expected output:
10
20
30
Important: The number of variables must exactly match the number of values. Otherwise, Python raises a
ValueError.
a, b = 10, 20, 30
Output:
ValueError: too many values to unpack (expected 2)
Practical Use: Swapping Two Variables
Multiple assignment makes swapping values simple, without needing a temporary variable:
x = 5
y = 9
x, y = y, x
print(x, y)
Expected output:
9 5
Assigning the Same Value to Multiple Variables
You can assign one value to several variables at once. This is useful when multiple variables should start with the same initial value.
x = y = z = 100
print(x)
print(y)
print(z)
Expected output:
100
100
100
All three variables now refer to the same value.
Caution: With a mutable value such as a list,
a = b = []makes both names refer to the same list object, so changing the list through one name is visible through the other. For lists, create separate objects instead:a = []andb = [].
Unpacking a Collection Into Variables
Unpacking takes the items from a collection — such as a list or tuple — and assigns them to individual variables in one step.
Unpacking a List
colors = ["red", "green", "blue"]
first, second, third = colors
print(first)
print(second)
print(third)
Expected output:
red
green
blue
The number of variables must match the number of items in the collection. Unpacking makes code cleaner, because you do not need to write colors[0], colors[1], and colors[2].
Collecting Remaining Items With *
If you only need some of the items, a variable prefixed with * collects the remaining items into a list:
scores = [95, 88, 76, 64, 50]
top, *others = scores
print(top)
print(others)
Expected output:
95
[88, 76, 64, 50]
Displaying Variables
The print() function is the most common way to display the value stored in a variable.
message = "Learning Python is fun"
print(message)
Expected output:
Learning Python is fun
Printing Multiple Variables Together
Separate variables with commas to print them in one statement. Python automatically adds a space between the values.
word1 = "Coding"
word2 = "with"
word3 = "Python"
print(word1, word2, word3)
Expected output:
Coding with Python
This approach works with any combination of data types.
Using the + Operator With Strings
The + operator joins (concatenates) strings. It does not add spaces automatically, so you must include them yourself.
a = "Python "
b = "makes "
c = "sense"
print(a + b + c)
Expected output:
Python makes sense
Without the trailing spaces inside the strings, the output would be Pythonmakessense.
Using + With Numbers
With numeric values, + performs addition instead of concatenation.
num1 = 15
num2 = 25
print(num1 + num2)
Expected output:
40
Mixing Strings and Numbers
Python does not allow you to combine a string and a number with +, because it cannot know whether you want addition or concatenation.
age = 30
name = "Rahul"
print(age + name)
Output:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Recommended Ways to Print Mixed Data
The simplest approach is to separate values with commas:
roll_no = 12
student_name = "Rahul"
print(roll_no, student_name)
Expected output:
12 Rahul
Another widely used approach is an f-string, which inserts variable values directly into text:
print(f"Roll number {roll_no} belongs to {student_name}")
Expected output:
Roll number 12 belongs to Rahul
Global and Local Variables
Where a variable is created determines where it can be used. This is called the variable's scope.
Global Variables
A global variable is created outside of any function. It can be read from anywhere in the program, including inside functions.
site_name = "GoCourse"
def show_site():
print(site_name)
show_site()
Expected output:
GoCourse
The function can read site_name even though the variable was not created inside it. Global variables are useful when several parts of a program need to share the same data.
Local Variables
A variable created inside a function is a local variable. It exists only while the function runs and can be used only inside that function.
language = "Python"
def display_language():
language = "Java"
print(language)
display_language()
print(language)
Expected output:
Java
Python
Explanation:
languageinside the function is a local variable with the value"Java".languageoutside the function is a global variable with the value"Python".- They have the same name, but they are separate variables. Assigning to
languageinside the function creates a new local variable; it does not change the global one.
Modifying a Global Variable With the global Keyword
To change a global variable from inside a function, declare it with the global keyword. Without it, Python treats the variable as local.
count = 1
def increase_count():
global count
count += 1
increase_count()
print(count)
Expected output:
2
global count tells Python that count inside the function refers to the global variable, so count += 1 updates it.
Without the global statement, the same function fails:
count = 1
def increase_count():
count += 1 # Python treats count as local here
increase_count()
Output:
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Because count is assigned inside the function, Python considers it local — but it has no value yet when count + 1 is evaluated. (The exact wording of this message varies slightly between Python versions.)
Creating a Global Variable Inside a Function
The global keyword can also create a new global variable from inside a function:
def set_status():
global status
status = "Active"
set_status()
print(status)
Expected output:
Active
After the function runs, status is available throughout the program. Note that status does not exist until set_status() has been called.
Best Practices for Global Variables
- Use global variables sparingly.
- Prefer passing values into functions as arguments and getting results back with
return. - Avoid modifying global variables unnecessarily — it becomes hard to track which function changed a value.
- Use clear, meaningful names for global variables.
The preferred alternative to modifying a global variable looks like this:
def increase(value):
return value + 1
count = 1
count = increase(count)
print(count)
Expected output:
2
The function receives a value and returns a result, so its behavior is easy to understand and test.
Common Mistakes
| Mistake | Example | Problem |
|---|---|---|
| Using a variable before assigning it | print(total) | NameError: name 'total' is not defined |
| Wrong letter case | Score instead of score | Refers to a different (or missing) variable |
| Invalid name | first-name = "Asha" | SyntaxError |
| Unpacking mismatch | a, b = [1, 2, 3] | ValueError |
Joining text and numbers with + | "Age: " + 25 | TypeError |
Forgetting global when modifying | count += 1 inside a function | UnboundLocalError |
Best Practices
- Use descriptive names in snake_case.
- Use UPPERCASE names for values meant to stay constant, such as
TAX_RATE = 0.18. - Avoid using built-in names like
list,str, orinputas variable names. - Keep variables local to functions whenever possible.
Related Concepts
- Python Data Types — the kinds of values a variable can hold
- Python Type Casting — converting values between types
- Python Functions — where local and global scope matter most