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
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”.
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
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)
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)
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)
3- Lists
A list contains items separated by commas and kept within square brackets ([]).
Example:
a = [11,12.3,'PythonGuides']
print(a)
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)
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)
These are the Python variable type.
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()
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)
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()
These are the Python variable scope.
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 declare 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
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)
This is how we can create a Python global variable by using the global keyword.
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
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
This is how to create a static variable in Python.
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 an iterable sequence of Unicode characters. Unicode was declaring to include every character in all languages and bring in encoding.
- It is a sequence of characters within the single and double quotes.
- To declare a string variable in Python, we have to add an iterable sequence of characters 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
This is how to create a Python string variable.
Create a dummy variable in python
- In this section, we will learn about how to create a dummy variable in python.
- Dummy variables are helpful whenever you are doing any machine learning task because all of the machine learning libraries take the numerical data from the existing data.
- Build the machine learning model on top of it. But in a real-world dataset, there are chances you have the combination of numerical data as well as categorical data.
- A dummy variable is a binary value that gives a signal of whether a separate categorical variable takes on a specific value.
- In this method, we will declare three variables of the countries name and using the function 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 the same length equal to the no. of columns when calling get_dummies on a DataFrame as df.
- Dummy_na: Add a column to get signal NaNs, if False NaNs are ignored.
- Returns: DataFrame(Dummy-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 code first, we will import all required modules, Declare a dataset using the dictionary method.
- Display the dataset by using data variables.
- Create variables by using the function get_dummies
Here is the Screenshot of the following given code
Create a empty variable in python
- In this section, we will learn about how to create a empty variable in python.
- Python is a programming language so there is no need to create such type of variable, it automatically declares when a first-time value assigns to it.
- To create an 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 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 method and range(start, stop) to sequence iterate over a range from start to stop.
- Inside the for loop using the string formatting syntax d[] = value to map many different keys indict 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