Python Variables (with Examples)

In Python, a variable is used to store and manipulate data. We can think of a variable as a named container that holds a value.

In this Python tutorial, learn the basics of Python variables, and the difference between local and global variables. Also, learn about global keywords used inside the functions in Python.

1. Python Variable Naming Convention

While Python is flexible with variable names, there are a few rules and conventions:

  • Variable names must start with a letter (a-z, A-Z) or an underscore (_).
  • Variable names can contain letters, numbers, and underscores.
  • Variable names are case-sensitive, meaning myVariable and myvariable are considered different variables.
  • Avoid using reserved words (e.g., if, for, while) as variable names.

Python 3 has full Unicode support, which allows for Unicode characters in a variable name as well.

2. Declaring a Variable in Python

Python language has no keyword for declaring a variable. Declaring a variable is as simple as assigning a value to a name. We don’t need to specify the variable’s data type explicitly. Python infers the variable’s type based on the assigned value.

2.1. Simple Variable Assignments

Consider the following example where we are creating 3 variables of type integer, string and list.

# Assigning an integer value to a variable
age = 25

# Assigning a string value to a variable
name = "Alice"

# Assigning a list of numbers to a variable
scores = [90, 85, 88, 92]

A variable of string type can be created with either single quotes or double quotes.

author = 'Lokesh'

blogName = "howtodoinjava"

2.2. Chained Assignments

Python also allows chained assignment, which makes it possible to assign the same value to several variables simultaneously.

i = j = k = 20

print(i)			# prints 20
print(j)			# prints 20
print(k)			# prints 20

2.3. Declaring Multiple Variables in One Line

In Python, we can declare multiple variables in a single line by separating them with commas and assigning values to each of them.

Declaring multiple variables in one line can be especially useful when we want to initialize several related variables at once or when we are unpacking values from data structures like lists or tuples.

# Declare and initialize multiple variables in one line
x, y, z = 10, 20, 30

# Print the values of the variables
print("x:", x)
print("y:", y)
print("z:", z)

2.4. Variable Re-declaration

As variables do not need datatype information, we can reassign a new value of any type without any problem. In Python, a variable may be assigned a value of one type and then later re-assigned a value of a different type.

index = 10
index = 20
index = "NA" # index is now a string variable

print(index)	# prints NA

3. Local and Global Variables in Python

In Python, variables can have different scopes, primarily local and global. The scope of a variable determines where the variable can be accessed or modified.

3.1. Local Variable

Local variables are defined within a specific function or block of code. They have a limited scope, meaning they can only be accessed and manipulated from within that particular function or block.

Once the function or block exits, the local variable typically goes out of scope and is no longer accessible.

def my_function():
    # This is a local variable
    x = 10
    print("Inside the function, x =", x)

my_function()
# Attempting to access x here would result in an error

In the above example, x is a local variable defined within the my_function function. It can only be used within that function.

3.2. Global Variable

Global variables are defined at the top level of application code, outside of any function or block. They have a broader scope and can be accessed and modified from anywhere in the code, including within functions.

# This is a global variable
y = 20

def my_function():
    # Accessing the global variable within the function
    global y
    print("Inside the function, y =", y)
    y = 30  # Modifying the global variable

my_function()
print("Outside the function, y =", y)

Program output:

Inside the function, y = 20
Outside the function, y = 30

In the above example, y is a global variable defined outside the my_function function. It can be accessed from within the function by using the global keyword.

As a best practice, we should never modify global values for any reason. They should be final and immutable variables for sharing application context-level information only.

4. Python Variable Examples

Let us see a few simple Python programs to understand how to use the variables in Python.

4.1. Calculating the Area of a Rectangle

# Define variables for length and width
length = 10
width = 5

# Calculate the area
area = length * width

# Print the result
print("The area of the rectangle is:", area)

4.2. Concatenating Strings

# Define variables for first and last name
first_name = "John"
last_name = "Doe"

# Concatenate the names
full_name = first_name + " " + last_name

# Print the full name
print("Full Name:", full_name)

4.3. Working with Lists

# Define a list of fruits
fruits = ["apple", "banana", "cherry"]

# Access and print the second item in the list
print("Second fruit:", fruits[1])

# Add a new fruit to the list
fruits.append("orange")

# Print the updated list
print("Updated list of fruits:", fruits)

Drop me your questions related to Python variables.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode