Trending October 2023 # Explained With Codes &Amp; Output # Suggested November 2023 # Top 13 Popular |

Trending October 2023 # Explained With Codes &Amp; Output # Suggested November 2023 # Top 13 Popular

You are reading the article Explained With Codes &Amp; Output updated in October 2023 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested November 2023 Explained With Codes &Amp; Output

What are Python Variables?

Python Variables are memory spaces that hold information, such as numbers or text, that the Python Code can later use to perform tasks.

Here is an example of a variable in Python:

Year = 2023

In the above code, the variable Year holds the assigned value 2023.

To understand Python variables better, imagine there is an empty shelf where you want to store a few items. But, before placing anything on the shelf, you add a label to each item so that you can search for anything easily by looking at the label.

In the same way, in Python programming, variables are like those labels. Here, we can say that the memory space is like an empty shelf. There you can store different types of values (items) like numbers, decimals, letters, and sentences. However, to store that data, we need to use variables (labels) so that Python can access the data using the variables.

So, when we create a variable and assign it a value, Python stores that value (item) in the memory (shelf) and remember the variable name (label).

Table of Contents

Python Variable Naming Convention

Before we start writing or declaring variables in Python, it is important to understand the rules for naming variables. Below are the 5 most important  Python variables rules you must know:

Example: _educba, xyz, ABC

Examples of incorrect variable names: 1variable, 23alpha, 390say

Example: learn_educba, c5, A777_21

Examples of different variable names: educba, Educba, EDUCBA

Example: while, if, print, while

Apart from this, it is also possible to create variable names with more than one word. There are 3 types of cases you can use to write multi-word variable names.

Case Types


Variable Name Example

1. Camel Case

The first word should be lowercase.

Capitalize the first letter of every word that follows.

There should be no space between the words.



2. Pascal Case

The first letter of each word should be in uppercase.

There should be no space between the words.



3. Snake Case

Add an underscore between each word as a separator.

There should not be any space between words.

You can freely use uppercase and lowercase letters.



 Python Variable Types

Python variable types, also known as variable data types, show the type of data stored in the variable.

The above image provides a brief overview of the different types of Python variables with examples. However, you should read the detailed explanation below to better understand each variable type.

1. Integer

A Python integer or int refers to whole numbers that can be either positive or negative.

c = 30000

Code for Printing Integer Variables:

a = 1 b = -200 c = 30000 print("a =",a) print("b =",b) print("c =",c)

Note: You can also verify the output of the other codes in this article by simply copying and pasting them into the compiler. You can use any other compiler of your choice to check the output.

2. Float

A Python float variable allows you to store decimals or floating-point values.

c = 5.8976

Code for Printing Float Variables:

a = 1.23 b = 4.567 c = 5.8976 print("a =",a) print("b =",b) print("c =",c)

3. String

A string variable in Python allows us to store letters, words, or sentences. To declare a string variable, you must write the letter, word, or sentence in double quotes.

c = “A Python Code”

Code for Printing String Variables:

a = "A" b = "Python" c = "A Python Code" print("a =",a) print("b =",b) print("c =",c)

4. Boolean

A boolean variable stores only two values, True or False. We use them for logical operations, like checking if a condition is true or false. We don’t enter the true or false in quotes for declaring a boolean as we do for strings.

b = False

Code for Printing Boolean Variables:

a = True b = False print("a =",a) print("b =",b)

5. List

A Python list is a variable that can store a group of values. To declare a list variable, write each word within square brackets, separated by commas.

a = [“John”,”Sam”,”Michele”]

Code for Printing a List Variable:

a = ["John","Sam","Michele"] print("a =",a)

6. Dictionary

A Python dictionary is a variable that can store any number of pairs of data (Eg, “Item”:”Jam”, “Fruit”:”Apple”). We can use a dictionary when we want to store numerous values for a single variable.

Employee1 = {“Name”:”Alan”,”ID”:1234,”Role”:”Analyst”}

Code for Printing a Dictionary Variable:

Employee1 = {"Name":"Alan","ID":1234,"Role":"Analyst"} print(Employee1)

7. Tuple

Tuples are variables that can store a collection of different data types in order. Moreover, after creating the variable, the programmer cannot make any changes to the values.

Today_Date = (“Monday”,”19th”,”June”,2023)

Code for Printing a Tuple Variable:

Today_Date = ("Monday","19th","June",2023) print("Today_Date =", Today_Date)

8. Set

A set variable in Python is very similar to a tuple variable (where we store a list of data). However, unlike a tuple, a set variable allows us to modify its elements when necessary.

Prime_nums = {2,3,5,7}

Code for Printing a Set Variable:

Prime_nums = {2,3,5,7} print("Prime_nums =",Prime_nums)

Working with Python Variables

There are 5 ways in which we can work with Python variables, from declaration to deletion.

Python Variable Declaration: Giving a value to a new variable

Variable Assignment: Giving a new value to an already declared variable

Variable Manipulation: Manipulating a variable for a specific result

Printing the Variable: Displaying the result value of a variable

Variable Deletion: Removing a variable from memory

Let us explore each stage in detail using the following code as an example.

# Variable Declaration Location = "Switzerland" Location, Flight_Number = "Switzerland", "GEN300" Location = Destination = "Switzerland" # Variable Assignment Location = "New York" # Variable Manipulation Tourist_spot = Location + " Empire State Building" # Printing the Variable print("Destination is",Location) print("I am going to",Location,"to visit",Tourist_spot) # Deleting the Variable del Location print("Location variable is deleted") print(Location)

Let us understand how you can use the above code. We will see how the above code works by analyzing each section of the code. We have also added outputs wherever necessary.

1. Python Variable Declaration

In the above example code, we first declare the variable by assigning it a value. To declare a variable, you must use the equal sign (=) after the variable name and then assign a value to it.

In Python, you have the option to either declare a single variable at a time or declare multiple variables simultaneously.

Single Variable Example:

Location = "Switzerland"

In this case, the variable Location will store the value of Switzerland. You can then use the variable throughout your code.

Python also allows you to assign values to multiple variables in a single line, known as multiple assignments.

Multiple Variables Example:

Location, Flight_Number = "Switzerland", "GEN300"

Note: Each variable on the left side of the equal sign corresponds to the value on the right side in the same position.

We can also assign the same value to multiple variables:

Location = Destination = "Switzerland" 2. Assigning a New Value

After declaring a variable, you can assign a new value to it at any point in your code. This allows you to update the value stored in the variable.


Location = "New York"

Here we are changing the value that Location holds from Switzerland to New York.

3. Variable Manipulation

After declaring a variable and assigning a value to it, you can perform various operations on it. This includes mathematical calculations, string manipulation, or any other relevant operations based on the variable’s data type.

For Example:

Location = "New York" Tourist_spot = Location + " Empire State Building"

Here, we are assigning the value of Location (New York) plus the words Empire State Building to the variable Tourist_spot. Thus, the variable Tourist_spot will store the words: New York Empire State Building. Remember to add a space before the second word Empire State Building to ensure proper spacing in the new variable. Otherwise, the resulting word will be New YorkEmpire State Building.

4. Print Python Variables

To see the value stored in a variable, you can use the print() function. This allows you to display the variable’s value in the output. To print a single variable, just mention the name of the variable inside the brackets of the print() function.


print("Destination is",Location)

This will print the value stored in the variable Location.

To print multiple variables, just mention all variables in the print function.


print("I am going to",Location,"to visit",Tourist_spot)

5. Deleting the Variable

In Python, you can also delete a variable when it is no longer needed. This frees up memory resources. You can use the del keyword followed by the variable name to delete it.


Location = "New York" print(Location) del Location print("Location variable is deleted") print(Location)

Here, Python deletes the variable ‘Location’ that we created at the beginning. Now the Python compiler holds no memory of Location or its value.

Thus, it prints the value New York in the beginning, but after deleting the variable, it shows a NameError.

Python Variables Example (With Code and Output)

Let’s say you wish to print a movie name and its rating in Python. Hence, you must first declare two variables for each value and then use the print() function.

Note: In the below code, we have added # before a line which makes it like a sticky note for our reference. It won’t affect the program’s execution or output.


# Declaration movie = "Inception" rating = 8.8 # Printing the movie print("Movie:", movie) # Printing the rating print("Rating:", rating)

Let us now delete the rating variable and try printing the variable again.


# Continuing the Code # Deleting the variable del rating # Printing the movie print("Movie:", movie) # Trying to print the rating after deletion print("Rating:", rating)

As we have deleted the variable, Python shows the NameError stating that the variable is not defined.

Type Conversion in Python

Apart from declaration, printing, and deletion, we can perform various other operations on variables. One of the most common is type conversion.

It means changing a variable’s current data type to another data type. For example, changing an integer to a string. The programmer can do this manually, or the Python compiler will do it automatically. Let us see each method in detail.

1) Implicit Type Conversion

When Python automatically changes the data type of a variable without the programmer’s instructions, it is known as Type Conversion.


num = 10 result = num + 5.5 print(result)

Here, we were trying to add an integer and a decimal number. However, both are different types, so Python automatically converts the integer (10) into decimal (10.0) and gives us a decimal number 15.5 (10.0 + 5.5) as the answer.

2) Explicit Type Conversion

When a programmer specifically tells Python to change the data type of a variable, it is known as explicit type conversion or typecasting.


# Adding an integer and a string num = 10 message = "The number is: " result = message + str(num) print(result)

Note: If we do not ask the compiler to use str(num) for the conversion, we will get a TypeError, as shown in the image below.

What is Object Reference?

An object reference explains how Python creates and uses a variable.

For instance, when we declare a variable: Num = 10, Python will execute the following steps.

Python first creates an object of the required data type. (Eg, Python creates an object with the integer data type)

Python then stores the value we assign within that object. (Eg, Python stores the value 10 in the integer object)

Finally, it creates a pointer, where the variable name we gave points to the object. (Eg, the variable Num will point to the integer object)

Therefore, Python uses the variable as a reference point for the object. So, when it wants to use the value stored in the variable, it will simply look where that variable is pointing.

For example, let us understand how Python creates a variable for the following declaration using a simple image:

Name = "John"

Moreover, if you want to check what type of object Python has created for your variable, you can use the type() function.


Name = "John" print(Name) print(type(Name))

Python Object Identity

We just saw how Python creates an object to store a value, and we know Python accesses the object to use the value. Therefore, every object must have a unique location, right?

So, in Python, every object has a special number called an identifier, which is like a unique fingerprint for each object. The identifier tells Python the object’s location.

If you want to know the Python object id, you can use the id() function.


name = "John" my_list = [1, 2, 3] print(id(name)) print(id(my_list))

In this example, we defined two variables: name and my_list. We then requested Python to display the identifier numbers of both variables using the id() function. As a result, Python displays each variable’s identifier number (numerical memory address).

Note: The object ID may change each time you run the code. It happens because once the code stops running, Python deletes all variables from the memory. When we run the code again, Python creates the variables again. Hence, each variable’s id keeps changing.

Python Variable Scope

After understanding the different Python variables and data types and the different operations, we can perform using them, let us dive a little into the scope of variables.

The scope of a variable tells the Python compiler which parts of the code can access and use the variable. There are two types of scopes: Local and Global.

To understand the concept of scope, let us see the local and global variables in Python.

1. Local Variable & Scope

When we declare a variable within a function, only that function can access the variable. It means we cannot use that particular variable anywhere outside the function. This is called local scope.

For instance, if you buy Adobe Photoshop, you can only use the Photoshop features and not the other Adobe features.

Example of Using a Variable Within Scope:

To use a variable within scope, we will first create a function called appreciate() that declares and prints a variable called text. Afterward, we will call the function to see how the local scope works.

def appreciate(): text = "Good job!" print(text) appreciate()

Example of Using a Variable Outside Scope:

Now let us see what happens if we try accessing the text variable without calling the appreciate() function.

def appreciate(): text = "Good job!" print(text)

Here, as text is a local variable declared inside the appreciate() function, we can only use it inside that function. So, when we try accessing the text outside the function, the output shows an error.

2. Global Variable & Scope

Unlike local variables, we can use global variables in any part of the program. They are available for use throughout the program until the code finishes running or the variable is intentionally deleted. It is necessary to declare global variables at the start of the program outside any functions or classes.

For instance, if you purchase a subscription to the Adobe Creative Cloud, you can freely use any Adobe software included in the subscription till the subscription ends or you voluntarily cancel the subscription.


In this example, we begin by declaring the global variable text at the beginning of the program. We then use this variable both inside and outside of a function called appreciate().

text = "Good job!" def appreciate(): print(text) appreciate() print(text)

This shows we can access and modify the text variable from anywhere in the code.

Frequently Asked Questions (FAQs)

For example, you assign the value Soccer to a variable named Sports. But later, if you want to change it to Cricket, you can simply write the code as:

Sports = Cricket

By doing this, Python will automatically ignore the Soccer value and only use Cricket.

Answer: In Python, defining an empty variable is an easy task. Developers can directly assign a null value to any variable using the None keyword. For example, let’s say the variable name is var, so to assign a null value developer can write it as:

var = None

The above declaration means that there is no value assigned to var.

Answer: It is convenient to add two Python variables using a Python + operator. You can add both numbers and strings in Python.


a = 5 b = 10 print(a + b) c = "EDU" d = "CBA" print(c + d)

Recommended Articles

We hope that this EDUCBA article on Python variables and Python variable types was helpful for a deep understanding of the concept of variables in Python. You can view EDUCBA’s recommended articles for more information.

You're reading Explained With Codes &Amp; Output

Update the detailed information about Explained With Codes &Amp; Output on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!