Python Variables
A variable in Python is used to store information that can be reused later in a program. You can think of it as a label attached to a value, allowing you to refer to that value by name.
Creating Variables in Python
Python does not require any special keyword to create a variable. A variable is automatically created when you assign a value to it for the first time.
Example:
count = 12
username = "Alice"
print(count)
print(username)
In this example, Python determines the type of each variable based on the value assigned to it.
Type Casting
Sometimes, you may want to explicitly convert a value from one data type to another. This process is called type casting.
Example:
num_text = str(45) # Converts number to string
num_value = int("20") # Converts string to integer
decimal = float(8) # Converts integer to float
print(num_text, num_value, decimal)
Casting is useful when working with user input or performing calculations.
Checking the Data Type
You can find out the type of any variable by using the built-in type() function.
Example:
price = 99.99
status = "Available"
print(type(price))
print(type(status))
This helps in debugging and understanding how data is handled in your program.
Using Single or Double Quotes
Strings in Python can be written using either single quotes (' ') or double quotes (" "). Both formats work exactly the same way.
Example:
city = "Chennai"
language = 'Python'
Choose one style and use it consistently in your code.
Case Sensitivity in Variable Names
Python treats uppercase and lowercase letters as different. This means variable names that look similar but differ in case are considered separate variables.
Example:
score = 85
Score = "Excellent"
print(score)
print(Score)
Here, score and Score are two distinct variables, and one does not affect the other.
Naming Variables in Python
In Python, variable names can be very short (such as i or n) or more meaningful and descriptive (like student_age, total_marks, or file_count). Using clear names makes your code easier to understand and maintain.
Rules for Valid Variable Names
Python follows strict rules when naming variables:
- A variable name must begin with a letter (a–z, A–Z) or an underscore (_)
- It must not start with a number
- Only letters, numbers, and underscores are allowed
- Variable names are case-sensitive
- Python keywords (such as for, if, class) cannot be used as variable names
Examples of Valid Variable Names
The following variable names follow all Python naming rules:
user = "Ravi"
user_name = "Ravi"
_user_id = 101
userName = "Ravi"
USERNAME = "Ravi"
user2 = "Ravi"
Examples of Invalid Variable Names
The variable names below will cause errors because they break Python’s naming rules:
3user = "Ravi" # Cannot start with a number
user-name = "Ravi" # Hyphens are not allowed
user name = "Ravi" # Spaces are not allowed
Naming Variables with Multiple Words
When a variable name contains more than one word, it’s important to format it in a readable way. Python developers commonly use the following naming styles:
Camel Case
The first word starts with a lowercase letter, and each following word begins with an uppercase letter.
totalPriceAmount = 2500
Pascal Case
Every word in the variable name starts with a capital letter.
TotalPriceAmount = 2500
Snake Case
All words are lowercase and separated using underscores.
This is the most recommended style in Python.
total_price_amount = 2500
Using meaningful variable names and consistent naming styles greatly improves code readability and professionalism.
Assigning Multiple Values to Variables in Python
Python allows you to assign multiple values to multiple variables at the same time using a single statement. Each variable receives the value in the corresponding position.
Example:
a, b, c = 10, 20, 30
print(a)
print(b)
print(c)
⚠️ Important: The number of variables must exactly match the number of values. Otherwise, Python will raise a ValueError.
Assigning the Same Value to Multiple Variables
You can also assign one value to several variables at once. This is useful when multiple variables should start with the same initial value.
Example:
x = y = z = 100
print(x)
print(y)
print(z)
All three variables now refer to the same value.
Unpacking a Collection into Variables
Unpacking allows you to take values from a collection—such as a list or tuple—and assign them to individual variables in one step.
Unpacking a List
When unpacking, the number of variables must match the number of items in the collection.
Example:
colors = ["red", "green", "blue"]
first, second, third = colors
print(first)
print(second)
print(third)
This technique makes your code cleaner and eliminates the need to access elements using indexes.
Displaying Variables in Python
The print() function is commonly used to display the value stored in a variable.
Example:
message = "Learning Python is fun"
print(message)
This prints the value assigned to the variable on the screen.
Printing Multiple Variables Together
You can display more than one variable in a single print() statement by separating them with commas. Python automatically adds spaces between the values.
Example:
word1 = "Coding"
word2 = "with"
word3 = "Python"
print(word1, word2, word3)
This method is simple and works well with different data types.
Using the + Operator with Strings
The + operator can be used to join (concatenate) string values together. When doing this, you must manually include spaces where needed.
Example:
a = "Python "
b = "makes "
c = "sense"
print(a + b + c)
If spaces are not added inside the strings, the output will appear merged without gaps.
Using + with Numbers
When used with numeric values, the + operator performs addition instead of concatenation.
Example:
num1 = 15
num2 = 25
print(num1 + num2)
The result displayed is the sum of the two numbers.
Mixing Strings and Numbers
Python does not allow you to combine a string and a number using the + operator directly. Doing so results in a type error.
Incorrect Example:
age = 30
name = "Rahul"
print(age + name)
This causes an error because Python cannot automatically convert between different data types.
Recommended Way to Print Mixed Data
The safest and easiest way to print multiple variables—especially when they contain different data types—is to separate them with commas inside the print() function.
Example:
roll_no = 12
student_name = "Rahul"
print(roll_no, student_name)
Python automatically handles the formatting, making this approach ideal for beginners.
Global Variables in Python
A global variable is a variable that is created outside of any function. Once defined, it can be accessed from anywhere in the program, including inside functions.
Global variables are useful when multiple parts of a program need to share the same data.
Creating and Using a Global Variable
When a variable is declared outside a function, it automatically becomes global.
Example:
site_name = "GoCourse"
def show_site():
print(site_name)
show_site()
In this example, the function can access site_name even though it was not created inside the function.
Global vs Local Variables
A variable created inside a function is called a local variable. Local variables can only be used within that function.
Example:
language = "Python"
def display_language():
language = "Java"
print(language)
display_language()
print(language)
Output:
Java
Python
Here:
- language inside the function is a local variable
- language outside the function is a global variable
- They are treated as separate variables
Using the global Keyword
If you want to modify a global variable inside a function, you must use the global keyword. Without it, Python will create a new local variable instead.
Example:
count = 1
def increase_count():
global count
count += 1
increase_count()
print(count)
The global keyword tells Python to use the variable defined outside the function.
Creating a Global Variable Inside a Function
You can also create a global variable from inside a function by using the global keyword.
Example:
def set_status():
global status
status = "Active"
set_status()
print(status)
After the function runs, status becomes available throughout the program.
Best Practices for Global Variables
- Use global variables sparingly
- Prefer passing values as function arguments
- Avoid modifying global variables unnecessarily
- Use clear and meaningful names for globals
Overusing global variables can make programs harder to debug and maintain.
