Create Python Variables – Complete tutorial

In this Python tutorial, we will discuss Create Python Variables and also cover the below examples:

Create a variable in python
Create a global variabe in python
Python declare variable
Python variable type
Python variable scope
Create a global variabe in python
Python private variable
Python protected variable
Static variable in Python
Create a string variable in python
create a dummy variable in python
create a empty variable in python
Create variable in python loop
create environment variable in python
Python create a variable name dynamically
Python create a variable bound to a set
python create a variable name from a string
Python create a variable and assign a value
Python create a variable in a loop
Python create a variable without value
Python create variable for each item in list
Python create variable if not exist
Python create a random variable
Python create a boolean variable
Python make a string variable raw

Python variable

A variable is nothing but a container that stores information or values. In another way, a python variable is like a memory location where you store values or some information. Now, this value has stored you may or may not to changed in the future.

Python declare variable

To declare a Python variable we just have to assign a value to it. You don’t have to give any additional commands unlike any other programming languages like C, Java where you have to give additional commands for declaration and assigning purpose.
If you want to specify the data type of a variable, this can be done with casting.
To create a variable, you just assign it a value and then start using it.

Example:

Let’s take an example to check how to create a variable in python.

x = 100
y = “John”
print(x)
print(y)

In the above example, we have two variables X and Y and we have assign value to each of them.
We have given 100 to X and John to Y . So this is actually how you create a variable in python.

Here is the Screenshot of the following given code

Create a variable in python

Here is another example.

In Python, You no need to mention the type while declaring the variable. This is the reason python is known as dynamically typed.

When we assign the value to this, during the same time, based on the value assigned python will determine the type of the variable and allocates the memory accordingly.

Example:

A = 19
B = “Python”

Here, A and B are two variables that contain the values 19 and Python respectively.

Python can understand that A is an integer variable seeing the value as “19” and B is a string variable seeing the value as “python”.

Read: Python check if the variable is an integer

Assign and reassign value to a variable

When you want to assign a value to a variable, you need to use the “=” operator. The left side of the “=” operator is the variable name and the right side is the value assigned to it.

Examples:

a = 1
b = 11
c = 11.1
d = “Python”

print(a)
print(b)
print(c)
print(d)

Let’s run the above code and see the output. The output should be

1
11
11.1
Python

Assign value to a variable

We got the expected output. See above.

How to reassign a variable

You can reassign a variable in python meaning suppose you have assigned a = 3 and again you can assign a different value to the same variable i.e a=”Hello”.

Example:

a=3
print(a)
a=”Hello”
print(a)

reassign value to a variable

Python variable multiple assignments

In Python, we can assign multiple variables in one line. To do this we have two approaches.

Approach-1:

Put all the variables in one line with multiple “=” operators and at the end we can keep the value.

Example:

a = b = c = d = 23

print(a)
print(b)
print(c)
print(d)

We can check the out put here

After executing the code, we got the above-expected output.

Approach-2:

Put all the variables with a comma separator and then put the “=” operator and then on the right side of the “=” operator put all the values with a comma separator.

Example:

a,b,c,d = 3
print(a)
print(b)
print(c)
print(d)

oops I got an error because you can not assign it in this way. Remember this. You will get an error “TypeError: cannot unpack non-iterable int object“. See below

Traceback (most recent call last):
File “C:/Users/Bijay/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Variable.py”, line 1, in <module>
a,b,c,d = 3
TypeError: cannot unpack non-iterable int object

So the correct way is as below. You need to specify a separate value for each one.

a,b,c,d = 3,4,5,6
print(a)
print(b)
print(c)
print(d)

You can also assign different types of values to each one.

Example:

a,b,c,d = 3,4.2,5,”PythonGuides”
print(a)
print(b)
print(c)
print(d)

multiple variables in python

Read: How to convert an integer to string in python

Python variable type

As we discussed already, a variable will be decided by the system where to allocate the memory based on their type. So let’s discuss few basic types of variables.

1- Number

This type of variable contains numeric values.

There are four types of numeric values are available in python

int

Example:

a = 11
print(a)

Long

a = 4568934L
print(a)
Note: Python 3.8 version doesn’t support a trailing L. It will show you invalid syntax.

Float

a = 11.5
print(a)

Complex

a = 55.j
print(a)

2- String

This type of variable contains string values. The string can be used with pairs of single or double-quotes.

Example:

s = “PythonGuides”

print(s)

s = ‘PythonGuides’

print(s)

Python variable types

3- Lists

A list contains items separated by commas and kept within square brackets ([]).

Example:

a = [11,12.3,’PythonGuides’]

print(a)

Python variable type

4- Tuples

A tuple is the same as lists but it is kept within parentheses ( () ). Items are separated by commas.

Example:

a = (11,12.3,’PythonGuides’)

print(a)

Python variable types

4- Dictionary

In Python, you can write dictionaries with curly brackets ( {} ). They have key and value pairs.

Example:

mydict = {
“good”: “Exposure”,
“Average”: “Knowledge”,
“Score”: 200
}
print(mydict)

Dictionary in python

These are the Python variable type.

Read: Python Concatenate Dictionary

Python variable scope

Let us discuss the python variable scope.

1- Local scope

A variable that is created inside a function has scope within that function. You can use that variable within that function. Let’s see an example

Example:

def myLocal():
a = 50
print(a)
myLocal()

Local scope

2- Global scope

The variable created outside the function or in the main body of the program is known as the Global scope.

Example:

a = 50
def myLocal():

print(a)
myLocal()
print(a)

Global scope

3- Enclosing Scope

In the below code, ‘b’ has local scope in myLocal() function and ‘a’ has nonlocal scope in myLocal() function. This is known as the Enclosing scope.

def myTest():
a = 50
def myLocal():
b = 3
print(a)
print(b)
myLocal()
print(a)
myTest()

Enclosing Scope

These are the Python variable scope.

Read: Python Check if a variable is a number

Create a global variabe in python

In this section, we will learn about how to create a global variable in python.
Global variable is a variable that can be accessed by anywhere.
A variable declared outside of the function or scope of variable in global that this variable is called global variable.
A global variable is also use outside or inside of the function or class.
To create a global variable in Python, you need to declare the variable outside the function or in a global scope.

Example:

Let’s take an example to check how to create a global variable in python.

n = 20

def funct1():
print(n)
def funct2():
print(n)
funct1()
#main
funct2()

In the above given example first I will create a variable n.
Now I will define a function called funct1() and print the value n.
After that I will define another function called funct2() print the value and call the function.
In the main I will call another function that is funct2().

Here is the Screenshot of the following given code

Create a global variable in python

There is another way to create a global variable in Python.

The use of the global keyword can make the variable global even though the variable is present inside the function. Let’s see an example.

Example:

def myLocal():
global a
a = 50
myLocal()
print(a)

Example-2:

If you want to change the value of a global variable inside a function

a = 150
def myLocal():
global a
a = 50
myLocal()
print(a)

Global Keyword in Python

This is how we can create a Python global variable by using the global keyword.

Read: How to add two variables in Python

Python private variable

By declaring your variable private you mean, that nobody can able to access it from outside the class.

In Python, adding two underscores(__) at the beginning makes a variable as private. This technique is known as name mangling.

Let’s see an example to see how exactly python private variables behave.

Example:

class Test:
__age = 30
def __Test2(self):
print(“Present in class Test”)
def Test3(self):
print (“Age is “,Test.__age)
t = Test()
t.Test3()
t.__Test2()
t.__age

see the output here

Age is 30
Traceback (most recent call last):
File “C:/Users/Bijay/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Variable.py”, line 9, in <module>
t.__Test2()
AttributeError: ‘Test’ object has no attribute ‘__Test2’

In the Test3() method, the __age variable can be accessed as shown above (age is printed). This is how to create a private variable in Python.

Python protected variable

By declaring your variable protected you mean, that it is the same as the private variable with one more advantage that they can be accessed in subclasses which are called derived/child classes

In Python, adding single underscores(_) at the beginning makes a variable protected.

Example:

class PythonGuides:
# protected variable
_name = “Raj”

def Test(self):
# accessing protected variable
print(“Name: “, self._name)
# creating objects of the class
p = PythonGuides()

# functions of the class
p.Test()

See the output

Name: Raj

Python protected variable

In the case of inheritance, the protected variable which is created in the parent class can be accessed in the derived class. This is how to create a protected variable in Python.

Static variable in Python

All the variables declared inside a class and outside the method are known as static variables. Static variables are also known as class variables.

There is no specific keyword in python to declare a static variable.

Example:

class Test:
var = 2 # static variable

print (Test.var) # prints 2 (static variable)

# Access with an object
obj = Test()
print (obj.var) # still 2

# difference within an object
obj.var = 3 #(Normal variable)
print (obj.var) # 3 (Normal variable)
print (Test.var) # 2 (static variable)

# Change with Class
Test.var = 5 #(static variable)
print (obj.var) # 3 (Normal variable)
print (Test.var )

See the output below

python static variable

This is how to create a static variable in Python.

Read: Python write variable to file + Examples

Create a string variable in Python

In this section, we will learn about how to create a string variable in python.
In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring in encoding.
It is a squence of characters enclosed within the single or double qoutes.
To create a string variable in Python, you have to add a sequence of character within single or double quotes.

Example:

Let’s take an example to check how to create a string variable in python

string1= “It’s my pen”
string2= ‘hello john’
print(string1)
print(string2)

In the above example, I have contains two strings. The first string is enclosed with the double-quotes. You can add a single-quoted character in the first string.
The second string is enclosed with the single-quotes where you cannot add any single quoted character in the first string.

Here is the Screenshot of the following given code

Create a string variable in python

This is how to create a Python string variable.

Read: Python remove substring from a String + Examples

Create a dummy variable in python

In this section, we will learn about how to create a dummy variable in python.
Dummy variable are helpful whenever you are doing any machine learning task because all of the machine learning libraries takes the numerical data from the existing data.
Build the machine learning model top of it. But in a real world dataset there are chances you have the combination of numerical data as well as categorial data.
A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. 
In this method we will create a three dummy variables of the countries name attribute and using the dunction get_dummies().

Syntax:

pandas.get_dummies
(
data,
prefix=None,
prefix_sep=’ ‘,
dummy_na=False,
dtype=None
)

It consists of few parameters

Data: Data of which to get dummy indicators.

Prefix: String to append DataFrame column names. Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame.

Dummy_na: Add a column to indicate NaNs, if False NaNs are ignored.

Returns: DataFrame(Dummy-coded data).

Example:

Let’s take an example to check how to create a dummy variable in Python.

import pandas as pd
import numpy as np

dataf = pd.DataFrame({‘Countries’: [‘Japan’, ‘Germany’, ‘U.S.A’, ‘AFRICA’],
})

print(dataf)
y = pd.get_dummies(dataf)
print(y)

In the above example first we import a required modules,Create a dataset using dictionary method.
Display the dataset by using dataf variable.
Create dummy variables by using the function get_dummies.

Here is the Screenshot of the following given code

Create a dummy variable in python

Read: Python compare strings

Create a empty variable in python

In this section, we will learn about how to create a empty variable in python.
Python is a dynamic programming language so there is no need to declare such type of variable, it automatically declares when first time value assign in it.
To create a empty variable in python,just assign none.

Example:

Let’s take an example to check how to create an empty variable in python

variable = None
print(variable)

Here is the Screenshot of the following given code

Create an empty variable in python

Create variable in python loop

In this section, we will learn about how to create a variable in python loop.
Use string formatting to create variables names while in a for-loop.
Use a for-loop and range(start, stop) to iterate over a range from start to stop .
Inside the for loop use the string formatting syntax d[] = value to map many different keys in dict to the same value.

Example:

Let’s take an example to check how to create a variable in a python loop

d = {}
for x in range(1, 6):
b= d[“string{0}”.format(x)] = “John”
print(b)

Here is the Screenshot of the following given code

Create variable in python loop

Read: Python For Loop with Examples

Create environment variable in python

In this section, we will learn about how to create environment variable in python.
Environment variables are implemented through the os package, specifically os.environ.
The simplest way to retrieve a variable from inside your application is to use the standard dictionary.
It is the set of key-value pairs for the current user environment.
They serve to configure Python in a consistent manner.

Example:

Let’s take an example to check how to create an environment variable in python

import os
user = os.environ[‘USER’]
print(user)

Here is the Screenshot of the following given code

Create environment variable in python

Python create a variable name dynamically

In this section, we will learn about how to create a variable name dynamically.
To Create a variable name dynamically we can easily use the for loop and the globals() method.
It is fundamentally a variable with a name that is the estimation of another variable.
Python is a dynamic programming language and it is possible to create Dynamic variables in Python.
Global method provides the output as a dictionary.
A dictionary has both a key and value, so it is easy to create a dynamic variable name using dictionaries.

Example:

variable = “b”
value = 6
dict2 = {variable: value}
print(dict2[“b”])

Here is the Screenshot of the following given code

Python creates a variable name dynamically

Read: Python naming conventions

Python create a variable bound to a set

In this section, we will learn about how to create a variable bound to a set.
bound variable is a variable that is previously free, but has been bound to a specific value or set of values.
To Create a variable bound to a set we can easily use the for loop and the globals() method.
It passes the instance as the first argument which is used to access the variables and functions.

Example:

Let’s take an example to check how to create a variable bound to a set

var=”apple”
apple1=()
apple2=()
apple3=()
for i in range(4):
globals()[ var+str(i)]=’a’

print(apple1)
print(apple2)
print(apple3)

Here is the Screenshot of the following given code

Python creates a variable bound to a set

Python create a variable name from a string

In this section, we will learn about how to create a variable name from a string.
To create a variable name from a string we can easily use the function exec().
The exec() function is used to execute the programm dynamically.

Example:

Let’s take an example to check how to create a variable name from a string by exec() method.

variable = ‘John’
John=[]
exec(“%s = %d” % (variable,10))
print(John)

In the above example first, we have a variable in which we are storing a string value john.
Inside the exec() function,we have %s and %d as a placeholder for string value and decimal value, respectively. It means that we assign an integer value to a string with the help of the assignment operator.

Here is the Screenshot of the following given code

Python creates a variable name from a string

Another way of doing this thing is by using the globals() method.
Global method provides the output as a dictionary.

Example:

Let’s take an example to check how to create a variable name from a string by using the globals() method.

str = “John”
John=[]
globals()[str] = 500
print(John)

In the above example first, we have taken an input in str as john.
Then we have to modify the value of a string through the globals() function.

Here is the Screenshot of the following given code

Python creates a variable name from a string by the globals method

Read: How to split a string using regex in python

Python create a variable and assign a value

In this section, we will learn about how to create a variable and assign a value.
To create a variable,you just assign it a value and then start using it.
The equal sign operator is used to assign values to variable.
In python programming language there has no command for declaring a variable.
You can also get the datatype of a variable with the type() function.

Example:

Let’s take an example to check how to create a variable and assign a value

x = 10
y = “Micheal”
print(x)
print(y)

In the above example, we have two variables X and Y and we have assign value to each of them.
We have given 10 to X and Micheal to Y . So this is actually how you create a variable in python.

Here is the Screenshot of the following given code

Python create a variable and assign a value

Python create a variable in a loop

In this section, we will learn about how to create a variable in a loop.
To create a variable in a loop we use a method for loop.
The Python for loop starts with the keyword “for” followed by an arbitrary variable name, which will hold the values of the following sequence object, which is stepped through.
First we will create a variable and taken the input values and characters in list or tuple and then after we will use the method for loop and print the variable.

Example:

Let’s take an example to check how to create a variable in a loop

languages = [“Python3”, “Java”, “Ruby”, “pascal”]
for language in languages:
print(language)

Here is the Screenshot of the following given code

Python create a variable in a loop

Read: Python While Loop Example

Python create a variable without value

In this section, we will learn about how to create a variable without value.
Python is a dynamic programming language so there is no need to declare such type of variable, it automatically declares when first time value assign in it.
To create a variable without value, we just assign a variable as None.

Example:

Let’s take an example to check how to create a variable without value.

variable = None
print(variable)

Here is the Screenshot of the following given code

Python create a variable without a value

Python create variable for each item in list

In this section, we will learn about how to create a variable for each item in list.
To create a variable for each item in list we can easily use the for loop method.
We can extract each list element by its index and then assign it to variables.
By using list comprehension we can run a loop for specific indices and assign them to the required variables.

Example:

Let’s take an example to check how to create a variable for each item in a list.

a,b,c = [1,2,3]
x,y,z = [str(e) for e in [a,b,c]]
print(x,y,z)

Here is the Screenshot of the following given code

Python create variable for each item in a list

Read: Python concatenate list with examples

Python create variable if not exist

In this section, we will learn about how to create a variable if not exist in Python.
In Python variables can be defined by locally or globally.Local variable is defined inside the function and global variable is defined outside the function.
To create a existence of local variable we are going to use local() function.

Example:

Let’s take an example to check how to create variables if not exist.

def func():

a_ = 0

local_variable = “a_” in locals()

print(local_variable)
func()

Here is the Screenshot of the following given code

Python creates variables if not exist

Python create a random variable

In this section, we will learn about how to create a random variable in Python.

Random integer values can be generated with the randint() function. This function takes two arguments: the start and the end of the range for the generated integer values.
In this method we can easily use the function randint().

randint() is an inbuilt function of the random module in Python.
First we will create a variable and assign the values in the randint() function and print the value .

Example:

Let’s take an example to check how to create a random variable

# generate random integer values
from random import randint
import random

value = randint(1,4)
print(value)

Here is the Screenshot of the following given code

Python creates a random variable

Python create a boolean variable

In this section, we will learn about how to create a boolean variable.
In python,boolean variables are defined by true or false.
In this case the variables that can have only two possible values: true, and false.
To create a boolean varaible we use the keyword bool.
The bool() method is used to return or convert a value to a Boolean value.

Example:

Let’s take an example to check how to create a boolean variable

def check(num):
return(bool(num%2==0))
num = 10;
if(check(num)):
print(“True”)
else:
print(“False”)

In the above example first we create a function check and pass the argument num.
The next step is we have to create a bool function and taken even condition to check the num variable is even or odd.
If the number is even it will print the result true otherwise false.

Here is the Screenshot of the following given code

Python create a boolean variable

Here is another scenario:

Here, boolean variables are defined by the True or False keywords.

An important thing to note here is True and False should be with the first letter as Uppercase. If you will write true and false it will show you an error. Let’s check this scenario.

Example

a = true;
b = True;
c = True if a == b else False
print (c);

Oops, I got the error on the very first line “NameError: name ‘true’ is not defined”.

The above error is because we did the mistake to mention true. It should be True (First letter Uppercase)

Now the correct syntax is

a = True;
b = True;
c = True if a == b else False
print (c);

Output will be as below

Python boolean variable

This is how to create a boolean variable in Python.

Read: Python Booleans

Python make a string variable raw

In this section, we will learn about how to make a string variable raw.
Raw strings do not treat backslashes(“”) as part of an escape sequence.
This is useful when we want to have a string that contains backslash and don’t want it to be treated as an escape character.
if we try to print a string with a “n” inside, it will add one line break. But if we mark it as a raw string, it will simply print out the “n” as a normal character.

Example:

Let’s take an example to check how to make a string variable raw

a = “HelloPythonguidesnHi”
print(a)

Here is the Screenshot of the following given code

Python makes a string variable raw

In this Python tutorial, we will discuss Create Python Variables and also cover the below examples:

Create a variable in python
Python declare variable
Python variable type
Python variable scope
Create a global variabe in python
Python private variable
Python protected variable
Static variable in Python
Create a string variable in python
create a dummy variable in python
create a empty variable in python
Create variable in python loop
create environment variable in python
Python create a variable name dynamically
Python create a variable bound to a set
python create a variable name from a string
Python create a variable and assign a value
Python create a variable in a loop
Python create a variable without value
Python create variable for each item in list
Python create variable if not exist
Python create a random variable
Python create a boolean variable
Python make a string variable raw

Flatlogic Admin Templates banner

Leave a Reply

Your email address will not be published. Required fields are marked *