What are Python Variables - Types of Variables in Python Language

What are Python Variables - Types of Variables in Python Language

29 Mar 2024
Beginner
4.73K Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Python Programming For Beginners Free Course

Python Variables: An Overview

In this Python Tutorial on computer programming, a variable is a value that can be changed, depending on conditions or information passed to the program. Python is a programming language with many features, and learning through a Python certification course can greatly enhance your programming skills. In this article we'll learn the concepts of variables in Python examples, and types of variables in Python.

Definition of Variables in Python

  • A variable is a named memory location in which a value is stored.
  • Any data type in Python, such as an integer, string, or list, can be used as the value.
  • Variables are used to store information that will be needed during the program.
  • In Python, you do not need to define a variable before using it.
  • When you assign a value to a variable, it is created.
  • You can change the value of a variable at any moment. This will override the variable's previous value.

Python Variable Naming Conventions

Variable naming conventions in Python are rules for defining meaningful and consistent variable names that improve code readability and maintainability. While Python does not require strict naming conventions, following them is commonly supported among Python programmers.

General Rules:

  • Begin with a letter (A-Z, a-z) or an underscore (_): Variable names should begin with a letter (A-Z, a-z) or an underscore (_). A variable name cannot begin with a number.
  • Use lowercase: Lowercase names for variables are preferred. This is a standard Python convention that helps readability.
  • Use underscores to separate words: When multiple words combine to make a variable name, use underscores instead of spaces to separate them. This is referred to as a snake_case.
  • Avoid reserved words: Do not use words reserved by Python for keywords, functions, or built-in data types, such as if, elif, else, def, class, import, and so on.
  • Maintain descriptive names: Select variable names that effectively reflect their purpose and meaning. Avoid ambiguous or general titles such as transient or data.
  • Unless they are common, avoid abbreviations: Only use abbreviations when they are well-known and obvious. For example, the count is superior to cnt.
  • Keep your naming consistent across your code: Maintain consistency in your codebase's naming approach. This simplifies the code's understanding and maintenance.

Read More - 50 Python Interview Questions and Answers

Declaration and Initialization of Variables in Python

Declaring and initializing variables in Python is a simple operation that comprises assigning a value to a variable using the assignment operator (=). Python, unlike other programming languages, does not require explicit variable declarations.

Declaration

Declaring a variable in Python is simply giving it a name. This name can be any valid identifier that follows naming rules such as beginning with a letter or underscore and containing alphanumeric characters, underscores, and digits.

Initialization

The process of providing an initial value to a variable is known as initialization. This value can be of any valid data type, including integers, strings, floats, booleans, and more complicated data structures such as lists, dictionaries, and sets.

Syntax of Declaring & Initializing Variable in Python

variable_name = value

Example of Declaring & Initializing Variable in Python Compiler

        # Declare a variable named 'age'
age = 25
# Declare a variable named 'name'
name = "Ram"
# Print the values of the variables 'age' and 'name'
print("My name is", name, "and I am", age, "years old.")

This code declares two variables, age, and name, and then prints the values of those variables to the terminal. The first line, age = 25, declares a variable called age and sets its value to 25. The second line, name = "Ram," establishes a variable named name and assigns the value "Ram" to it. Finally, the third line, print("My name is", name, "and I am", age, "years old.") outputs the names and ages of the variables to the console.

Output

My name is Ram and I am 25 years old.

How to create variables in Python?

Creating variables in Python is a simple process. Python, unlike other programming languages, does not require an explicit variable declaration. Variables are usually generated when you apply a value to them.

  • Select a variable name: The names of variables should be descriptive and belong to Python's naming rules. They can be made up of letters, digits, and underscores, but they must not begin with a number or contain special characters.
  • Assign a value: To assign a value to the variable, use the python's assignment operator (=). Any data type, such as integers, texts, floats, or booleans, can be used as the value.
  • Use variables: Once you've created a variable, you can use it to store and retrieve data throughout your program. To get the variable's value, simply refer to its name.

How does the + operator work with variables?

The Python plus operator + makes it easy to add a value if it is a number or concatenate a string. If a variable has already been created, the new value is assigned to the same variable.

How to print variables in Python?

The print() method in Python can be used to print variables. Simply put the variable name inside the print() function's parentheses.

Example of Printing Variables in Python

        x = 11
print(x)
The first line x = 11 declares a variable called x and assigns the value 11 to it.The second line print(x) prints x's value to the console. Because the value of x is 11, the code's output will be 11.

Output

11

Read More - Python Developer Salary in India

How to delete a variable in Python?

In Python, the del keyword is used to delete variables and objects. It removes the object's reference from the program's memory.

Example of Deleting a Variable in Python 

        name = "Ram"
print(name) 
del name
try:
  print(name)
except NameError:
  print("Variable 'name' is not defined")

The del statement is used in this Python Editor to delete the variable name. The try block was created to detect an error that occurs when you attempt to print a variable after it has been deleted. The unless block displays a message indicating that the variable is not defined.

Output

Ram
Variable 'name' is not defined

Multiple Assignment of Python Variables

The ability to assign numerous values to various variables in a single line of Python code is referred to as multiple assignment. This works by placing a comma-separated list of variables on the left side of the assignment operator (=) in Python and a corresponding list of values on the right.

Example of Multiple Assignment of Python Variables

a,b,c = 1,2,"Scholar Hat"
print (a)
print (b)
print (c)

This example assigns values to three variables (a, b, and c) in a single line (1, 2, and "Scholar Hat" respectively), which are then printed separately to show the values.

Output

1
2
Scholar Hat

Local and Global Variables in Python

There are two types of variables in the Python programming language, those variable names in Python are

  1. Python local variable
  2. Python global variable

Types of Variables in Python

Python Local Variable

  • A variable declared within a Python function is referred to as a local variable.
  • It exists simply within the function and cannot be accessed from anywhere else.
  • When the function is called, local variables are generated and removed when the function returns.

Example of Python Local Variable

        def sum(x,y):
 sum = x + y
 return sum
print(sum(5, 10))

In this example in the Python Online Compiler, the function "sum" is defined to take two parameters, add them, store the result in the variable "sum," and then return that sum. With the values 5 and 10, the function is run, and the output (15) is displayed on the console.

Output

15

Python Global Variable

  • A global variable in Python is a variable with a global scope, which means it can be accessed from anywhere in the program, including within functions.
  • Global variables are declared outside of any Python function and are normally defined at the program's start.

Example of Python Global Variable

        counter = 0
def increment_counter():
    global counter
    counter += 1
increment_counter()
increment_counter()
increment_counter()
print(counter)

The counter variable is declared outside of the increment_counter() function in this example. It is thus a global variable that can be accessed from anywhere in the program. The global keyword is used by the increment_counter() function to access the global variable counter. Because the function also creates a local variable with the same name, this is required. The function could only access the local variable if the global keyword was not used.

Output

3
Summary

In this article, we learned that variables in Python examples, types of variables in Python variables are used to store values, and they are classified by their type. By taking the time to learn about the different types of variables and how to use them effectively, you can make your Python programming faster, easier, and more efficient by gaining a deeper understanding of variables through Python Certification Training.

FAQs

Q1. 1. What are the 4 types of variables in Python?

In Python, there are four different types of variables: int, float, str, and bool.

Q2. 2. What is an integer variable in Python?

In Python, full numbers without decimals are stored in integer variables.

Q3. 3. How many variables are in Python?

Python allows you to define as many variables as you need.

Q4. 4. How do I define a variable?

Use a name, python assignment operator, and a value to define a variable.

Q5. 5. What are the uses of variables?

Python programs store and operate on data using variables.

Q6. 6. How do you write a variable in Python?

Use a name (like "my_variable") and a value (like "= 10") to create a variable in Python.
Share Article
Batches Schedule
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this