How to use Variables in Python3?


Variables are fundamental elements in programming that allow us to store and manipulate data. In Python 3, variables are dynamically typed, meaning they can hold different types of data throughout their lifetime. Understanding how to use variables effectively is crucial for writing robust and flexible code. In this article, we will understand the use of variables in Python with the help of different examples.

Variable Basics

In Python, variables are created by assigning a value to a name using the "=" operator. The name of the variable is chosen by the programmer and should follow certain naming conventions. Variable names are case-sensitive and can include letters, numbers, and underscores. However, they cannot start with a number or contain any special characters.

Example

In the below example, we created three variables: name, age, and height. The name variable holds a string value, the age variable holds an integer value, and the height variable holds a floating-point value. We then printed the values of these variables using the print() function.

# Variable assignment
name = "John"
age = 25
height = 1.75

# Accessing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)

Output

Name: John
Age: 25
Height: 1.75

Variable Types

Python 3 supports various built-in data types, including integers, floats, strings, booleans, and more. Variables in Python are dynamically typed, meaning they can change their type during runtime.

Example

In the below example, we first assign an integer value to the variable x and print its type, which is <class 'int'>. Then, we assign a floating-point value to x and print its updated type, which is <class 'float'>. Finally, we assign a string value to x and print its type, which is <class 'str'>. This demonstrates how variables can change their type as needed.

# Variable types
x = 10
print("x is of type:", type(x))  # Output: <class 'int'>

x = 3.14
print("x is now of type:", type(x))  # Output: <class 'float'>

x = "Hello, World!"
print("x is now of type:", type(x))  # Output: <class 'str'>

Output

x is of type: <class 'int'>
x is now of type: <class 'float'>
x is now of type: <class 'str'>

Variable Naming Conventions

While naming variables, it's essential to follow certain conventions to write clean and readable code. Here are some commonly accepted guidelines for variable naming in Python:

  • Use descriptive names: Choose names that accurately describe the purpose or content of the variable. For example, instead of x or var1, use names like age, name, or user_input.

  • Use lowercase with underscores: To improve readability, use lowercase letters for variable names. If the name contains multiple words, separate them using underscores. For example, first_name or num_students.

  • Avoid reserved keywords: Do not use Python reserved keywords, such as for, while, if, else, or class, as variable names. These words have special meanings in Python and are used for specific purposes.

  • Be consistent: Follow a consistent naming convention throughout your codebase to maintain uniformity. This will make it easier for you and others to understand and maintain the code.

Variable Scope

Variables in Python have a specific scope, which defines where the variable can be accessed and used. The scope of a variable is determined by where it is defined within the code. There are two main types of variable scope in Python: global and local.

Global scope: Variables defined outside any function or block have global scope. These variables can be accessed from anywhere within the program.

Example

In the below example, the variable x is defined outside the print_global() function, making it a global variable. The function can access and use this variable without any issues.

# Global scope
x = 10

def print_global():
    print("Global variable x:", x)

print_global()  # Output: Global variable x: 10

Output

Global variable x: 10

Local scope: Variables defined within a function or block have local scope. These variables can only be accessed from within the function or block where they are defined.

Example

In the below example, the variable y is defined inside the print_local() function, making it a local variable. It can only be accessed within the function. Attempting to access y outside the function will result in a NameError.

def print_local():
    y = 5
    print("Local variable y:", y)

print_local()  # Output: Local variable y: 5
print("Trying to access y outside the function:", y)  # Error: NameError: name 'y' is not defined

Output

Local variable y: 5

NameError: name 'y' is not defined

Variable Reassignment

In Python, variables can be reassigned to different values at any point in the program. This flexibility allows us to update and modify the values stored in variables.

Example

In the below example, we initially assign the value 5 to x and print it. Then, we reassign x to the sum of its current value and 10. Finally, we reassign x to a string value. Each time we reassign the variable, its value changes accordingly.

# Variable reassignment
x = 5
print("Initial value of x:", x)  # Output: Initial value of x: 5

x = x + 10
print("Updated value of x:", x)  # Output: Updated value of x: 15

x = "Hello"
print("New value of x:", x)  # Output: New value of x: Hello

Output

Initial value of x: 5
Updated value of x: 15
New value of x: Hello

Variable Operations

Variables can be used in various mathematical and logical operations. Python allows us to perform operations on variables of compatible types.

Example

In the below example, we perform various arithmetic operations on variables a and b, such as addition, subtraction, multiplication, division, and modulus. We also perform logical operations like greater than, less than, and equality checks.

# Variable operations
a = 10
b = 3

# Arithmetic operations
sum_result = a + b
difference_result = a - b
product_result = a * b
division_result = a / b
modulus_result = a % b

# Logical operations
greater_than = a > b
less_than = a < b
equals = a == b

print("Sum:", sum_result)  # Output: Sum: 13
print("Difference:", difference_result)  # Output: Difference: 7
print("Product:", product_result)  # Output: Product: 30
print("Division:", division_result)  # Output: Division: 3.3333333333333335
print("Modulus:", modulus_result)  # Output: Modulus: 1
print("Greater than:", greater_than)  # Output: Greater than: True
print("Less than:", less_than)  # Output: Less than: False
print("Equals:", equals)  # Output: Equals: False

Output

Sum: 13
Difference: 7
Product: 30
Division: 3.3333333333333335
Modulus: 1
Greater than: True
Less than: False
Equals: False

Constants and Variable Naming Conventions

Although Python doesn't have built-in support for constants, it is a common convention to use uppercase names to represent constant values. While the value of a constant can still be changed in Python, it serves as a visual indication that the value should remain constant and not be modified.

Example

In the below example, PI and GRAVITY are treated as constants with uppercase names, even though they can still be reassigned. We calculate the area of a circle using the constant PI and the radius variable.

# Constants
PI = 3.14159
GRAVITY = 9.8

radius = 5
area = PI * radius ** 2
print("Area of the circle:", area)

Output

Area of the circle: 78.53975

Conclusion

In this article, we discussed how we can use variables in Python3 and learned about understanding the basics of a variable assignment, types, naming conventions, scope, reassignment, operations, constants, and multiple assignments, which can be used in different scenarios and effectively use variables to write powerful and flexible Python code.

Updated on: 13-Oct-2023

108 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements