A variable in Python is a name that refers to a value stored in memory. You can use variables to store data such as numbers, strings, lists, and more. Variables let you reuse values, perform calculations, and pass information around in your programs.
= operator to store a value in a variable.myVar and myvar are different variables.In Python, you create a variable the moment you first assign a value to a name using the = operator. There is no need to declare the type; Python infers it from the value.
Variable names must:
_.You can also assign multiple values in a single statement or assign the same value to multiple variables. To display values, use the built-in print() function, often combined with formatted strings (f-strings) for cleaner output.
A global variable is defined outside functions. Inside a function, you can modify it using the global keyword.
x = 10
name = "Alice"
price = 99.99
valid_name = "Python"
_name = "Valid"
name1 = "Also valid"
# 1name = "Invalid" # ❌ starts with number
a, b, c = 1, 2, 3
print(a, b, c)
x = y = z = 100
print(x, y, z)
name = "Alice"
age = 25
print("Name:", name)
print("Age:", age)
print(f"My name is {name} and I am {age} years old.")
x = "global"
def show():
global x
x = "modified"
print("Inside:", x)
show()
print("Outside:", x)
For the multiple assignment example:
a, b, c = 1, 2, 3
print(a, b, c)
x = y = z = 100
print(x, y, z)
The output will be:
1 2 3
100 100 100
For the global variable example, the function changes the value of x for the entire program:
x = "global"
def show():
global x
x = "modified"
print("Inside:", x)
show()
print("Outside:", x)
The output will be:
Inside: modified
Outside: modified
Because of the global keyword, the assignment inside show() updates the same x that is used outside the function.
user_name over just x or y.total_price).f-strings for clean, readable string output with variables.Name and name are different.NameError.name, age, and city. Print them in one line using an f-string.a, b, and c in a single line and print their sum.