9303753286127016 How To Create Python Variables - Complete Tutorial

How To 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
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”.

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
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
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

python variable multiple assignment

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
Python variable multiple assignment using python 3.8

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)
python variable naming conventions

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)
Assignment of multiple variable in python
multiple variables 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 type
Python variable types

3- Lists

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

Example:

a = [11,12.3,'PythonGuides']

print(a)
How many types of variables are there in python
Python variable type

4- Tuples

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)
Tuples in python
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
Dictionary in python

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()
Local variable scope in python
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 variable in python
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 variable in python
Enclosing Scope

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

Create a global variable in python
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)
Global keyword in python

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 variable in python
Global Keyword in Python

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'
Private python variable

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
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

how to create a static variable in python
python static variable

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

Create a string variable in python
Create a string variable in python

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 dummy variable in Python
Create a dummy variable in python


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 a empty variable in python
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 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

Create variabe in python loop
Create variable in python loop

Create environment variable in python

  • In this section, we will learn about how to create environment variable in python.
  • Environment variables are implemented via the os package, generally 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 and manage the Python library 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
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 declare a variable name dynamically we can use the for loop method 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.
  • The global method provides the output as a dictionary.
  • A dictionary has both the key and value pair, 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 create a variable name dynamically
Python creates a variable name dynamically

Python create a variable bound to a set

  • In this section, we will learn about how to create a variable bound to a set.
  • Abound variable is a variable that is previously free but has been bound to a specific value or set of values.
  • To Create a var bound to a set we can use the for loop method and the globals() method.
  • It passes the instance as an object the first parameter 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 create a variable bound to a set
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 create a variable name from a string
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 update the element of a string through the globals() method.

Here is the Screenshot of the following given code

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

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 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 a loop.
  • The Python for loop method starts with the keyword “for” followed by a variable name, which will hold the values of the following object, which is stepped through.
  • First, we will create a variable and taken the input values and characters in a 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
Python create a variable in a loop

Python create a variable without value

  • In this section, we will learn and discuss how to create a variable without value.
  • Python is a dynamic language so there is no need to create such type of variable, it automatically declares when the first-time value assigns to it.
  • To create a variable without a 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 value
Python create a variable without a value

Python create variable for each item in list

  • To create a variable for each item in the 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 variabe for each item in list
Python create variable for each item in a list

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 locally or globally. A local variable is defined inside the function and a global variable is defined outside the function.
  • To create an existence of a local variable we are going to use the 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 create variable if not exist
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 originated with the randint() function. This function takes two parameters the start and the last of the range for the generated integer values.
  • In this method, we can easily use the function randint().
  • randint() is a function of the random module in Python.
  • First, we will declare a variable and pass 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 create a random variable
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 as true or false.
  • In this case, the variables can have only two possible values: true, and false.
  • To create a boolean variable we use the keyword bool.
  • This bool() function 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
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

How to create boolean variable in python
Python boolean variable

This is how to create a boolean variable in Python.

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 the main method when we have a string that contains backslash and don’t want it to be treated as an escape character.
  • if we won’t try to print a string with a “\n” inside, it will add one new line break. But if we mark it as a string, it will simply print out the “\n” as a character.

Example:

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

a = "Hello\Pythonguides\nHi"
print(a)

Here is the Screenshot of the following given code

Python make a string variable raw
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 rawCreate 
Balkishan Agrawal

At the helm of GMS Learning is Principal Balkishan Agrawal, a dedicated and experienced educationist. Under his able guidance, our school has flourished academically and has achieved remarkable milestones in various fields. Principal Agrawal’s vision for the school is centered on providing a nurturing environment where every student can thrive, learn, and grow.

Post a Comment

Previous Post Next Post