Python Variables

What are Variables?

Python Variables are defined as a name or identity given to a specific memory location to access those locations easily in our code using these names. It can be created by typing the variable's name, then an equal to "=" operator, followed by the variable's value. The value defined for a variable can be changed if needed.

For Example:

			

customer = 'John'
amount = 1000

				

Like, in the above code snippet, the customer's name and amount are variable Identifiers.

Assigning Values to Variables

Python uses the assignment operator = to create and assign a variable.

You need to specify the variable name and assign a value to it. The variable is created once a value is assigned to it; therefore, there is no need to create it in advance. A variable cannot be declared without a value.

The Syntax is.

<variable name> = <value>

Variable type declaration

Unlike other languages like C++ or Java, python explicitly determines the variable's data type. So, there is no need to mention the type of variable with the variable name.

For Example: -

			

invoice_no = 5           #invoice_no is an integer

print(type(invoice_no))

customer = 'John'    #customer is now a string

print(type(customer))

				

Output:

<class 'int'> <class 'str'>

Assigning Multiple Variables in Python

Python allows us to assign multiple variables with their name in a single statement.

The example creates three variables var1, var2 and var3, in a single statement and assigns a value of 50 to all

			

var1 = var2 = var3 = 50

print(var1)

print(var2)

print(var3)

				

Output:

50 50 50

Also,

			

var1, var2, var3 = 1, 2, 3

print(var1)
print(var2)
print(var3)

				

Output:

1 2 3

Reading variable values:

You can use the Python print() statement to output variable values to the browser. In the following example, two variables, Length and Breadth, are assigned some values. You are finding the perimeter of the rectangle here and printing it.

			

Length = 20

Breadth  = 15

print( 2 * (Length + Breadth) )

				

Output:

70

Another way is to assign the value of variables to other variables to manipulate them or keep using them later. The perimeter of the rectangle is stored in the rectange_perimeter variable, and you can use it later on or print it.

			

Length = 20

Breadth  = 15

rectange_perimeter = 2 * (Length + Breadth) )
print(rectange_perimeter)

				

Output:

70

Python variable naming rules:-

Some rules need to be followed while naming variables. The rules are as follows:

1. The variable's name should start with either an alphabetical letter or an underscore(_). For example, _myvariable, myvariable, my_variable are valid variable names.

			

#valid variable names
myvariable = 10
my_variable = 10
_my_variable = 100

print(my_var)
print(_my_var)

				

Output:

10 100

The variable's name should not be initiated with a number. For example, 7my_variable is an invalid variable name.

			

#invalid variable names
7my_variable = 50

				

Output:

SyntaxError: invalid syntax

The variable's name cannot include special characters like %, $, #, etc. It must only contain alphanumeric characters(A to Z, a to z, 0-9) and underscore(_).

			

#invalid variable names
my_variable$ = 50
%variable = 100

				

Output:

SyntaxError: invalid syntax

Variable names are considered case-sensitive in Python. For example, my_variable and My_variable are two different variables. So, you need to be careful about uppercase and lowercase alphabets.

			

my_variable = 100
print(My_variable)

				

Output:

NameError: name 'My_variable' is not defined.

Python Type Casting

Data type of a variable can be specified via typecasting.

			


x = str(3)   
print(type(x))

y = int(3)   
print(type(y))

z = float(3) 
print(type(z))

				

Output:

<class 'str'> <class 'int'> <class 'float'>

Data Types in Python

The variable's data type defines the type/kind of data stored by a variable. Python explicitly and automatically assigns variables the suitable data type. So, there is no need to mention the data type to the variables in Python programming language.

			

x = 10
y = 'Hello'
z = 5.5
print(type(x))
print(type(y))
print(type(z))

				

Output:

<class 'int'> <class 'str'> <class 'float'>

In the above example, the variable x is assigned with an integer value, and Python automatically sets the data type of x as an int type.

Python Number Data Types

These data types handle numeric data. Integer numbers, float numbers, and complex numbers are considered under number data types.

Int - It includes positive or negative whole numbers. There is no limit in Python on the length of an integer, so an integer can be of any length.

			

x = 10
print(type(x))

				

Output:

<class 'int'>

Float - It covers real numbers represented in the floating-point format. It is accurate up to 15 decimal points.

			

z = 5.5
print(type(z))

				

Output:

<class 'float'>

Complex - It covers complex numbers that has a real and an imaginary part.

			

y = 3 + 5j
print(type(y))

				

Output:

<class 'complex'>

Python Boolean Data Type

It can hold only two values, either True or False and denoted by class bool. Any non-zero value can be true, while False is represented by 0 only.

			

x = (1 == True)

y = (1 == False)

a = True + 4

b = False + 10

print("x is", x)

print("y is", y)

print("a:", a)

print("b:", b)

				

Output:

x is True y is False a: 5 b: 10

Python None Type

It is used as a placeholder and for the initialization of objects and variables.

			

apple = "Available"
orange = None

def menu(x):
   if x == apple:
       print(apple)
   else:
       print(orange)

menu(apple)
menu(orange)

				

Output:

Available None

Python Sequence Data Types

String - It is a collection of one or more character inside quotation marks. Strings are usually used to store text data. Note that strings are immutable in Python. Since String types are immutable in nature, all these methods first create a copy of the original string and then return a new string as a result.

			

str_1 = 'hello' #string str1   
str_2 = ' how are you' #string str2   
print (str_1[0:4]) #printing first 5 characters using slice operator   
print (str_1[1]) #printing 2nd character of the string   
print (str_1*3) #printing the string twice   
print (str_1 + str_2) #printing the concatenation of str1 and str2

				

Output:

hell e hellohellohello hello how are you

Some methods that are supported by Strings:-

Method Explanation
find() Search the string for a significant value and return its position
replace() Return a new string with a particular part can be exchanged/replaced with a given value
lower() Convert all the characters to lower case in the string
upper() Convert all the characters to upper case in the string
remove() Remove first element with a particular value
count() Get the count of a particular value in a string
capitalise() Convert the first character of the string to upperCase

Since the String type is immutable in nature, all these methods first create a copy of the original string and then return a new string as a result.

Python List - A list is a collection of elements. These elements are listed or written inside a [ ] square brackets separated by commas. Lists are mutable(modifiable). Lists can store elements of similar or different data types. Lists can also be used as stacks and queues by using the methods like append(), pop(), and dequeue().

			

my_list = [1, 2.2, 'list']

print(my_list)                         #print my_list

my_list_2 = [5,10,15,20,25,30,35,40]

print("my_list_2[2] = ", my_list_2[2]) #print 3rd character of my_list2

print("my_list_2[0:3] = ", my_list_2[0:3])#print first 4 characters of my_list2

print("my_list_2[5:] = ", my_list_2[5:]) #print all characters afther 5th character of my_list2

				

Output:

[1, 2.2, 'list'] my_list_2[2] = 15 my_list_2[0:3] = [5, 10, 15] my_list_2[5:] = [30, 35, 40]

In Python, lists support the following methods:

Method Explanation
append() Adds an element at the end of list
insert() Adds an element at the index position
sort() Sort the list
pop() Remove element at an index
remove() Remove first element with a particular value
index() Get index of a specified element
reverse() Reverse the list
clear() Remove all elements
copy() Copy the list
extend() Append elements if a list at the end of another list

Python Tuple - Tuples are also a collection of elements of different or similar types. The items of the tuple are separated with a comma (,) and enclosed in parentheses (). You can not modify Tuples after their creation as they are immutable in nature. The size of a tuple cannot grow or shrink after its creation. However, a tuple can be reassigned.

			

my_tuple  = ("hi", "Python", 2)   
# Checking the type of my_tuple 
print (type(my_tuple))   

#Printing the my_tuplele 
print (my_tuple) 

# Tuple slicing 
print (my_tuple[1:])   
print (my_tuple[0:1])   

# Tuple concatenation using + operator 
print (my_tuple + my_tuple)   

# Tuple repetition using * operator 
print (my_tuple * 3)    

# Adding value to my_tuple. It will throw an error. 
my_tuple[2] = "hi" 

				

Output:

<class 'tuple'> ('hi', 'Python', 2) ('Python', 2) ('hi',) ('hi', 'Python', 2, 'hi', 'Python', 2) ('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2) TypeError: 'tuple' object does not support item assignment

Tuples support the following methods:-

Method Explanation
count() Return count of a particular value
index() Return index of a particular value

Python Dictionary- Dictionary is a collection of different elements, written in an unordered manner in the form of Key:Value pairs. The elements are separated by commas "," and enclosed inside curly braces { }. As a dictionary is mutable in nature, so it's size can grow and shrink according to the requirement.

			

my_dictionary = {1:'value','key':2}

print(type(my_dictionary))

print("d[1] = ", d[1])

print("d['key'] = ", d['key'])

# Generates error
print("d[2] = ", d[2])

				

Output:

<class 'dict'> my_dictionary[1] = value my_dictionary['key'] = 2 KeyError: 2

Dictionary supports the following methods:-

Method Explanation
fromkeys() Return dictionary with particular key and value
get() Return value of a key
items() Return a list with all key value pair
pop() Remove element with a particular key
remove() Remove first element with a particular value
update() Update dictionary with particular key-value pairs
clear() Remove all elements
copy() Copy the dictionary
popitem() Remove last pair from dictionary

Python Sets - It is an unordered collection of unique elements. Sets are defined by values separated by commas inside braces { }. Elements in a set are not ordered. An item only appears once inside a set, no matter if it has been written multiple times inside the set. Being mutable in nature, sets can also grow and shrink as per requirement. Sets are not considered Sequences as they don't store items in an ordered manner.

			

my_set = {5,10,11,2,1}

# printing set variable
print("my_set = ", my_set)

# data type of variable a
print(type(my_set))

				

Output:

my_set = {1, 2, 5, 10, 11} <class 'set'>