Variables in Python

Photo by PiggyBank on Unsplash

Variables in Python

ยท

6 min read

A variable is a named reference to a value that can be changed or modified. A variable is created by assigning a value to a name, and this name can be used to access the value later on in the program.

Here is an example of creating and using a variable in Python:

my_age = 25
print(my_age)

In this example, we created a variable called my_age and assigned it the value 42. We then used the print function to display the value of the variable.

๐Ÿ’ก Complete Python Roadmap for beginners and experts.

Dynamic Typing

Python has dynamic typing, which means that the data type of a variable can change at runtime. This allows for greater flexibility and ease of use when writing code. Here is an example:

my_age = 25
print(my_age)

my_age = "Hello, World!"
print(my_age)

In this example, we start by assigning the value 42 to my_age, and then we print its value. We then assign the string "Hello, World!" to my_age, and print its value again.

Let's understand what is meant by a variable as a named reference first.

Variable Reference

In Python, variables are references to objects in memory. When you create a variable and assign a value to it, the variable is actually pointing to a location in memory where the value is stored. For example:

x = 5

In this case, x is a variable that points to a location in memory where the value 5 is stored.

You can use the id() function in Python to get the unique identifier of an object in memory. The id() function returns an integer that represents the memory address of the object. For example:

x = 5
print(id(x)) # 9793216

This code will output a unique integer value that represents the memory address where integer 5 is stored. When you assign a variable to another variable, you are creating a reference to the same object in memory. For example:

x = 5
y = x

In this case, both x and y are pointing to the same location in memory where the integer 5 is stored. You can verify this by using the id() function:

x = 5
y = x
print(id(x)) # 9793216
print(id(y)) # 9793216

This code will output the same integer value for both x and y, indicating that they are pointing to the same object in memory. If you modify the value of x, the value of y will also be affected since they are both pointing to the same object in memory:

x = 5
y = x
x = 6
print(y) # 5

This code will output 5, since y is still pointing to the original object in memory that contains the value 5. In Python, some types of objects are mutable, which means that their values can be changed. For example, a list is a mutable object:

x = [1, 2, 3]
y = x
x.append(4)
print(y)

In this case, both x and y are pointing to the same list object in memory. When we append the value 4 to the list using the append() method, the value of y is also affected since it is pointing to the same object in memory. This code will output [1, 2, 3, 4].

Variable Name Rules

Here are the specific rules for naming variables in Python:

  • Variable names must start with a letter or an underscore (_).

  • Variable names can only contain letters, numbers, and underscores (_).

  • Variable names are case-sensitive.

  • Variable names cannot be the same as a Python keyword.

Read more about naming variables in detail.

Types of variables i.e., data types

There are several types of variables in Python, each with its own characteristics and uses. Here are some of the most common types:

Integer Variables

An integer variable is used to store whole numbers. For example, 1, 2, 3, -4, -5, etc. Integer variables are represented using the int() function in Python.

age = 28
height = 170

Float Variables

A float variable is used to store decimal numbers. For example, 3.14, 2.5, -0.5, etc. Float variables are represented using the float() function in Python.

pi = 3.14
temperature = 25.5

Boolean Variables

A boolean variable is used to store either True or False values. Boolean variables are often used for logical operations in Python.

is_raining = True
is_sunny = False

String Variables

A string variable is used to store text data. For example, "Hello, World!", "Python Programming", etc. String variables are represented using either single or** double quotes** in Python.

name = "John"
message = "Hello, World!"

List Variables

A list variable is used to store a collection of data. For example, a list of numbers or a list of strings. List variables are represented using square brackets [] in Python.

numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]

Tuple Variables

A tuple variable is similar to a list variable, but it is immutable, which means it cannot be changed once created. Tuple variables are represented using parentheses () in Python.

coordinates = (10, 20)
colors = ("red", "green", "blue")

Dictionary Variables

A dictionary variable is used to store a collection of key-value pairs. For example, a dictionary of names and ages. Dictionary variables are represented using curly braces {} in Python.

person = {"name": "John", "age": 28, "height": 170}
scores = {"math": 90, "science": 85, "history": 75}

Set Variables

A set variable is used to store a collection of unique values. Set variables are represented using curly braces {} in Python.

unique_numbers = {1, 2, 3, 4, 5}
unique_colors = {"red", "green", "blue"}

You can also refer to this python syntax cheatsheet

Variable Scope

Variable scope refers to the area of a program where a particular variable is visible or accessible. In other words, it defines the parts of a program where a variable can be used and accessed.

In Python, there are two types of variable scope: global and local.

Global scope

A variable that is declared outside of a function or a class is considered to have a global scope. A global variable can be accessed from any part of the program, including inside a function or a class.

# declaring a global variable
global_var = "I am a global variable"

# accessing the global variable inside a function
def print_global():
    print(global_var)

# calling the function
print_global()   # output: I am a global variable

# accessing the global variable outside the function
print(global_var)   # output: I am a global variable

In this example, global_var is a global variable that is declared outside of the function. It can be accessed both inside and outside the function.

Local scope

A variable that is declared inside a function or a class is considered to have a local scope. A local variable can only be accessed within the function or class where it is declared.

# declaring a function with a local variable
def print_local():
    local_var = "I am a local variable"
    print(local_var)

# calling the function
print_local()   # output: I am a local variable

# trying to access the local variable outside the function
print(local_var)   # NameError: name 'local_var' is not defined

In this example, local_var is a local variable that is declared inside the function. It can only be accessed within the function, and trying to access it outside the function will result in a NameError.

Note: Local Scope Takes Precedence

Overall, Python variables are an integral part of the language and are crucial for any programmer to master.

๐Ÿ’ก Complete Python Roadmap for beginners and experts.

Did you find this article valuable?

Support Nitin Raturi by becoming a sponsor. Any amount is appreciated!

ย