Back to Python
2026-02-205 min read

Changing the Value of a Variable in Python

Learn Changing the Value of a Variable in Python step by step with clear examples and exercises.

Why This Matters

In this full guide, we will delve into the fundamental concept of changing the value of a variable in Python. By understanding how to modify variables, you'll be able to create dynamic programs that can adapt based on user input or changing conditions. This skill is crucial for solving real-world problems, debugging errors, and preparing for job interviews.

Prerequisites

To follow this guide effectively, it's essential to have a basic understanding of Python syntax, data types, and how to write simple programs. If you're new to programming or need a refresher on these topics, consider checking out our Python Basics tutorial first.

Core Concept

In Python, variables are used to store data and can be assigned values using the = operator. To change the value of a variable, simply reassign it with a new value:

x = 5
print(x) # Output: 5

x = 10
print(x) # Output: 10

Python automatically determines the data type of the variable based on the assigned value. For example, if you assign a number without a decimal point, Python will treat it as an integer; otherwise, it will be treated as a float.

Variable Scope

In Python, variables have either local or global scope. Local variables are defined within functions and only exist within that function. Global variables can be accessed from any part of the program. To declare a global variable, use the global keyword:

x = 5 # This is a global variable

def change_global():
global x
x = 10 # Changing the value of the global variable

change_global()
print(x) # Output: 10

Mutable and Immutable Types

Note that that some data types in Python, such as lists and dictionaries, are mutable, meaning their values can be modified. On the other hand, numbers, strings, and tuples are immutable, which means you cannot change their values directly:

Mutable types (lists and dictionaries)

my_list = [1, 2, 3]

my_dict = {'a': 1, 'b': 2}

my_list[0] = 5 # Changing the value of a list element

print(my_list) # Output: [5, 2, 3]

my_dict['c'] = 3 # Adding a new key-value pair to a dictionary

print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}

Immutable types (numbers, strings, and tuples)

my_number = 5

my_string = "Hello"

my_tuple = (1, 2, 3)

Attempting to change the value of an immutable type will result in an error

my_number += 1 # TypeError: 'int' object cannot be assigned to a mutable 'int'

Worked Example

Let's create a simple program that takes user input, stores it in a variable, and then changes its value based on user choice.

name = input("Enter your name: ")
print(f"Hello, {name}!")

choice = int(input("Choose an option (1 or 2): "))

if choice == 1:
new_name = "John"
print(f"Your name is now John.")
elif choice == 2:
new_name = "Sarah"
print(f"Your name is now Sarah.")
else:
print("Invalid option. Your name remains as ", name)

print(f"Hello, {new_name}!")

Common Mistakes

  1. Assigning a value to a variable without first declaring it: In Python, you don't need to declare variables before assigning them values, but this can lead to errors if the variable is used before being assigned. To avoid this issue, always ensure that every variable you use has been assigned a value before using it in your code.
  1. Changing the value of a constant: In Python, constants are typically defined using the const keyword or by making variables read-only with the = operator (e.g., x = 5). However, this is not strictly enforced, and changing their values can lead to unexpected behavior in your code. To prevent this mistake, avoid modifying constants unless absolutely necessary.
  1. Not understanding variable scope: Failing to understand the difference between local and global variables can cause issues when trying to access or modify them within functions or other scopes. Always make sure you declare your variables with the appropriate scope in mind.
  1. Modifying mutable data types directly within a function without using the global keyword: If you want to change the value of a global mutable data type inside a function, use the global keyword to ensure that the changes are reflected outside the function as well.

Practice Questions

  1. Write a program that takes two numbers as input, stores them in variables a and b, and then calculates their sum and product. Print both results.
  1. Create a function called increment_counter() that accepts a global counter variable count. Inside the function, increment the value of count by 1. Write a separate script that defines the count variable and calls the function multiple times to demonstrate its effect on the global variable.
  1. Modify the worked example to include a third option for changing the name based on user input.
  1. Create a program that takes a list of numbers as input, sorts it in ascending order using the sort() method, and then prints the sorted list.
  1. Write a function called reverse_list() that accepts a list as an argument and reverses its order. Test the function with a sample list.

FAQ

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

A: In Python, variables have dynamic types, meaning you can assign different data types to them without explicitly declaring their types. However, if you need to convert between data types, use built-in functions like int(), float(), and str().

Q: What happens when I try to change the value of a constant in Python?

A: In Python, constants are not strictly enforced, so changing their values will not cause an error. However, modifying constants can lead to unexpected behavior in your code and should be avoided unless absolutely necessary.

Q: How do I access global variables inside functions in Python?

A: To access a global variable inside a function, use the global keyword followed by the variable name before modifying it. For example:

x = 5 # This is a global variable

def change_global():
global x
x = 10 # Changing the value of the global variable

Q: How do I modify mutable data types directly within a function without using the global keyword?

A: To modify a mutable data type directly within a function without using the global keyword, pass the data type as an argument to the function. Inside the function, you can then modify its value and return it back to the calling scope for use.

my_list = [1, 2, 3]

def modify_list(lst):
lst[0] = 5 # Changing the value of a list element directly within the function
return lst

my_list = modify_list(my_list)
print(my_list) # Output: [5, 2, 3]
Changing the Value of a Variable in Python | Python | XQA Learn