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:
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:
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:
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:
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:
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:
Examples of Invalid Variable Names
The variable names below will cause errors because they break Python’s
naming rules:
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.
Pascal Case
Every word in the variable name starts with a capital letter.
Snake Case
All words are lowercase and separated using underscores.
This is the most recommended style in Python.
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:
⚠️ 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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
Output:
Java
Python
Try it YourselfHere:
- 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:
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:
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.
