Master Python Variables: Global vs. Local Scope Difference Explained in 6 Steps

Table of Contents

A Python variable is a name that refers to a value stored in the computer’s memory. It acts as a container that holds data, allowing you to reuse and manipulate it throughout your program.  A variable is created when a value is assigned to it.

				
					x = 10
y = "Hello"
z = 3.14

print(x)      # 10
print(y)      # Hello
print(z)      # 3.14
				
			

The above code demonstrates the variables. Here we first assign 10 to ‘x’, then “Hello” to y, and then ‘3.14’ to z. The variables can take any type, including numbers, floats, strings etc. and display them through the print statement. Python automatically understands the data type based on the value.

How to declare a variable in Python

While declaring a variable in Python certain rules should be followed:

  • It should start with a letter or an underscore (_)
  • Variables can only contain letters, numbers and underscores
  • It is case-sensitive (Name and name are different variables)
  • It Cannot start with a number
  • Cannot use Python keywords like if, for, while, etc
  • Examples:

           name = “Aveen”:           Valid
           _name = “Bob”:             Valid
           user1 = “Champ”:         Valid
           1user = “David”:            Invalid
           for = “Siri”:                     Invalid

 

Assigning Multiple Values to Multiple Variables and One Value to Multiple Variables

In Python multiple values can be assigned to multiple variables in a single line and at the same time we can also assign a single value to multiple variables wherever needed. Consider the example given below.

				
					a, b, c = "Cat", "Dog", "Pig"
x = y = z = "Apple"
print(a)                           # Cat
print(b)                           # Dog
print(c)                           # Pig
print(x)                           # Apple
print(y)                           # Apple
print(z)                           # Apple
				
			

EXPLAINATION

In the above example we have assigned multiple values like Cat, Dog, Pig etc to a,b,c in a single line. Then we assigned a single value “Apple” to multiple variables x,y,z. This helps to reduce the number of lines in the code.

 

Output Variables

An output variable is a variable in a programming context that is used to store the result or value produced by a function, method or program block. Consider the example below. 

				
					name = "Tom"
age = 20
print(f"My name is {name} and I am {age} years old.")

# output

#   My name is Tom and I am 20 years old

				
			

In the above code name and age is the output variable.

Output variables can also be used to perform various mathematical operations like ‘+’, ’- ’,  ‘*’,  ’/’   etc. Consider the example below.

				
					a=9
b=1
print(a+b)

# output

10
				
			

Here the output is 10 as the values of both variables are added and a similar operations can be performed with other operators.

While performing any mathematical operations with variables you must keep in mind that the data types must be the same especially with operators like ‘+’, ‘-‘ and ‘/’. Consider the example below with different data types which will throw an error.

				
					A=5
B= cat
Print(a-b)

# output

#  TypeError: unsupported operand type(s) for -: 'int' and 'str'


				
			

The above code displays an error as Python cannot interpret the operation for different data types.

But it will work for ‘*’ operation as the  ‘*’ operator when used between an integer (A = 5) and a string (B = “cat”), is defined to perform string repetition.

The best way to output multiple variables is to use a comma ‘,’ and display the output variables of different data types separately.

				
					A = 9
B = ”John”
Print(a,b)

# output

#  9 John
				
			

Type Casting a Variable

Type casting means converting a value from one data type to another. Python offers built-in functions for this.

int(): it converts a value to an integer.

float(): it converts the values to float

str(): it converts the value to string.

bool(): it converts the values to a boolean type.

Consider an example below.

				
					#  Convert string to integer
x = "10"
y = int(x)
print("String to Integer:", y, type(y))               # 10 <class 'int'>

#  Convert integer to float
a = 5
b = float(a)
print("Integer to Float:", b, type(b))                # 5.0 <class 'float'>

#  Convert number to string
num = 100
text = str(num)
print("Number to String:", text, type(text))          # 100 <class 'str'>

#  Convert values to boolean
print("Boolean of 1:", bool(1))                       # True
print("Boolean of 0:", bool(0))                       # False
print("Boolean of empty string:", bool(""))           # False
print("Boolean of 'Hi':", bool("Hi"))                 # True

				
			

Get the Variable Type

The type() function can be used to find the variable type.

				
					x = 10
y = "Hello"
z = 3.14
fruits = ["apple", "banana", "mango"]
is_active = True


print(type(x))                  # <class 'int'>
print(type(y))                  # <class 'str'>
print(type(z))                  # <class 'float'>
print(type(fruits))             # <class 'list'>
print(type(is_active))          # <class 'bool'>



				
			

Global and Local Variables in Python

Variables defined inside a function are local variables (they exist only within that function).

Variables defined outside any function are global variables (they can be accessed anywhere in the program)

				
					global_message = "I am a Global Variable (accessible everywhere)"

def set_messages():
    global global_message  # The fix: Declare global first
    local_number = 100
    
    print(f"Inside function (reading global): {global_message}")
    print(f"Inside function (reading local): {local_number}")
    
    global_message = "I am the MODIFIED Global Variable!"

set_messages()
print("\n--- After function call ---")
print(f"Outside function (global): {global_message}")

# output

# Inside function (reading global): I am a Global Variable (accessible everywhere)
# Inside function (reading local): 100

# --- After function call ---
# Outside function (global): I am the MODIFIED Global Variable!
				
			

In the above code global_message is the global variable (called outside the function) and local_number is the local variable(called inside the function) The global variable can also be modified inside the function as shown in the example above.

The global_message is declared outside the function but it is modified inside the function and again displayed outside the function.

 

Deleting a Variable

You can delete a variable by using the del keyword. Once the variable is deleted, trying to use it will result in an error as the variable is no longer available in memory.

				
					x = 10
del x   # deleting the variable
print(x)   #  name 'x' is not defined

				
			

Write a Python program to swap the variables

				
					a = 10
b = 20

a, b = b, a

print(a, b)    # 20 10
				
			

 FAQ (Frequently Asked Questions)

1. What is a variable in Python?

A variable is a name that refers to a value stored in the computer’s memory. Python assigns a data type automatically when a value is stored. It allows you to reuse and manipulate data easily throughout your program.

 

2. How to declare a variable in Python?

In Python you can declare a variable simply by assigning a value to a name no need to specify its type.

Example:

x = 5
name = "Tim"
pi = 3.14
 
 

3. How to print a variable in Python?

You can print a variable using the built-in print() function.

Example:

x = 5
print(x)
 

4. How to declare a global variable in Python?

A global variable is declared outside any function and can be accessed anywhere in the program.

Example:

x = 5

def change_x():
global x
x = 10  

change_x()
print(x) # Output: 10

 

5. What is an instance variable in Python?

An instance variable belongs to an object (instance) of a class. Each object has its own copy.

class Student:
def __init__(self, name):
self.name = name # instance variable

 

6) What are variable-length arguments in Python?

Arguments that allow a function to accept any number of values. *args is used to accept positional arguments, and **kwargs is used for keyword arguments.

 
def fun(*args):
print(args)

 

7) What is the Scope of variables in Python

Scope defines the region of a program where a variable name is recognized and can be used.

  • Local variables: accessed inside a function

  • Global variables: accessed outside all functions

  • Instance variables: accessed inside a class, accessed through objects

  • Class variables: it shared by all objects in a class

 

8. What is the difference between a global Variable and a Local Variable?

AspectGlobal VariableLocal Variable
DeclaredOutside all functionsInside a function
ScopeAccessible anywhereAccessible only inside the function
LifetimeExists until program endsExists only during function execution
Modification inside functionRequires global keywordModified normally
Memory locationGlobal frameLocal frame
UsageFor data used by many functionsFunction-specific data