Back to Python
2026-02-146 min read

Assigning values to Variables in Python

Learn Assigning values to Variables in Python step by step with clear examples and exercises.

Title: Assigning Values to Variables in Python

Why This Matters

In this comprehensive lesson, we delve into the fundamental concept of assigning values to variables in Python. Mastering this skill is essential for every programmer as it forms the backbone of writing efficient code, debugging errors, and preparing for interviews or exams.

Prerequisites

To follow along with this lesson, you should have a basic understanding of:

  • Python syntax (variables, operators)
  • Understanding of data types in Python (integers, floats, strings, etc.)
  • Familiarity with control structures such as if, for, and while statements
  • Basic knowledge of functions and modules

Core Concept

Variables are containers that hold values in Python. They allow us to store and manipulate data during program execution. By using variables, we can make our code more readable, maintainable, and efficient.

Declaring Variables

To create a variable, simply assign a value to it:

my_variable = 42
print(my_variable) # Outputs: 42

In the example above, we created a variable named my_variable and assigned it the integer value of 42. The print() function is then used to display the value stored in the variable.

Data Types

Python automatically determines the data type of a variable based on the value assigned:

integer_var = 42
float_var = 3.14
string_var = "Hello, World!"
bool_var = True
list_var = [1, 2, 3]
dict_var = {"key": "value"}

In the code above, we declared variables of different data types: an integer (integer_var), a float (float_var), a string (string_var), a boolean (bool_var), a list (list_var), and a dictionary (dict_var).

Variable Naming Conventions

When naming variables in Python, follow these best practices:

  • Use lowercase letters for variable names.
  • Separate words with underscores (_).
  • Avoid using reserved keywords as variable names.
  • Use meaningful and descriptive names for your variables to make the code more readable.

For example: my_variable, my_list, and my_function are valid variable names, while for, while, and print are not.

Multiple Assignments

You can assign multiple variables in a single line using the assignment operator (=):

x, y = 1, 2
print(x) # Outputs: 1
print(y) # Outputs: 2

In this example, we created two variables, x and y, and assigned them the values of 1 and 2 respectively.

Constant Variables

To declare a variable that cannot be changed (a constant), use the underscore prefix (_):

_PI = 3.14
print(_PI) # Outputs: 3.14
_PI = 3.15 # Raises an error, as _PI is a constant

In this example, we declared the variable _PI as a constant and assigned it the value of 3.14. Attempting to change its value raises an error.

Scope of Variables

Variables in Python can have different scopes: global, local, and built-in. Understanding their scope is crucial for managing variables effectively.

Global Variables

Global variables are accessible within the entire script or module:

global my_global = 0
def function():
global my_global
my_global += 1
print(my_global)
function()
print(my_global)

In this example, my_global is a global variable, and its value is incremented within the function(). The updated value of my_global remains accessible outside the function.

Local Variables

Local variables are only accessible within the function or block they are defined:

def function():
local_var = 0
print(local_var)
function()
print(local_var) # Raises an error, as local_var is not accessible outside its function

In this example, local_var is a local variable, and it can only be accessed within the function(). Attempting to access it outside the function raises an error.

Worked Example

Let's write a simple program that calculates the area of a rectangle using variables:

def calculate_area(length, width):
area = length * width
return area

length = int(input("Enter the length of the rectangle: "))
width = int(input("Enter the width of the rectangle: "))
area = calculate_area(length, width)
print("The area of the rectangle is:", area)

In this example, we created a function calculate_area() that takes two arguments (the length and width of a rectangle) and calculates its area. We then ask the user to input the length and width of a rectangle and calculate its area using the calculate_area() function. Finally, we print the calculated area.

Common Mistakes

  1. ### Forgetting to initialize a variable before using it
print(my_variable) # Raises an error as my_variable has not been initialized
  1. ### Assigning incompatible data types to a variable
integer_var = "42" # This assigns the string "42", not the integer 42
  1. ### Using reserved keywords as variable names
for = "Not a valid variable name" # Raises an error, as 'for' is a reserved keyword
  1. ### Shadowing variables (using the same variable name in nested scopes)
x = 1
def function():
x = 2
print(x) # Outputs: 2, as x within the function shadows the global x
print(x) # Outputs: 1, as we're still referring to the global x

In this example, x is a global variable with the value of 1. Within the function(), we created a new local variable named x with the value of 2. The value of x within the function shadows the global x.

Practice Questions

  1. Write a program that calculates the sum of two numbers entered by the user using variables.
  2. Write a program that determines whether a number entered by the user is even or odd using variables.
  3. Write a program that stores the names and ages of three people as variables and displays their details.
  4. Write a program that defines a function to calculate the factorial of a number (using recursion) and uses it to find the factorial of 5.
  5. Write a program that defines a function to calculate the Fibonacci sequence up to a given number (n) and uses it to generate the first 10 numbers in the Fibonacci sequence.
  6. Write a program that defines a function to convert temperatures between Celsius, Fahrenheit, and Kelvin using variables.

FAQ

### Can I change the data type of a variable in Python?

No, once a variable has been assigned a data type, it cannot be changed to another data type without converting its value first.

### How do I convert a string to an integer or float in Python?

Use the int() and float() functions respectively:

string_var = "42"
int_var = int(string_var) # Assigns the integer value of 42 to int_var

### What happens if I try to assign a value to a constant variable in Python?

Attempting to change the value of a constant variable raises an error, as it cannot be modified once declared.

### How do I access global variables within a function in Python?

To access a global variable within a function, use the global keyword:

global my_global = 0
def function():
global my_global
my_global += 1
print(my_global)
function()
print(my_global)

### How do I create a local variable that shadows a global variable in Python?

To create a local variable that shadows a global variable, simply assign the same name to a new variable within a function:

x = 1
def function():
x = 2
print(x) # Outputs: 2, as x within the function shadows the global x
print(x) # Outputs: 1, as we're still referring to the global x

### How do I check if a variable exists in Python?

To check if a variable exists in Python, use the locals() or globals() functions:

if "my_variable" in locals():
print("my_variable exists")
else:
print("my_variable does not exist")
Assigning values to Variables in Python | Python | XQA Learn