Operators in Python
Operators in Python
Operators in python
1.Python Operators in general are used to perform operations on values and variables.
2.The operator can be defined as a symbol which is responsible for a particular operation between two operands.
3.Operators are the pillars of a program on which the logic is built in a specific programming language.
4.Python provides a variety of operators, which are described as follows.
Arithmetic Operators
1.Arithmetic operators are used to perform arithmetic operations between two operands.
2.Arithmetic operators are used to performing mathematical operations like + (addition), - (subtraction),
*(multiplication), /(divide), %(reminder), //(floor division), and exponent (**) operators.
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Output
13
5
36
2.25
2
1
6561
Comparison Operators
1.Comparison operators are used to compare two values
2.Comparison operators are used to comparing the value of the two operands and returns Boolean true or false
according to the condition.
3.Comparison are also called as Relational operators compares the values.
Input
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Output
False
True
False
Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional
statements.
Input
# Examples of Logical Operator
a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
Output
False
True
False
Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers.
Input
# Print bitwise AND operation
print(a & b)
Output
0
14
-11
14
2
40
Assignment Operators
Assignment operators are used to assigning values to the variables.
Input
# Assign value
b=a
print(b)
Output
10
20
10
100
102400
Identity Operators
is and is not are the identity operators both are used to check if two values are located on the same part of the
memory. Two variables that are equal d
Input
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
Input
# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
2.Expain about Lists in Python?
List
1)List is a collection of elements separated by comma(,) enclosed in square brackets([])
2)all the elements in the list are heterogeneous in nature(we can declare both homogeneous and heterogeneous
elements)
3)list is ordered collection i.e what ever the order we insert or arrange the same order it fallow
4)list is index based collection
List allows duplicate elements
5)how to declare list
L=[]#empty list
L=[10,]# list with single value
L=[10,20,30,40] #list with homogenous values
L=[10,2.4,”hi”,True]#list with heterogeneous values
L=[10,20,[2,3,4],30]#we can place one list inside other list this is called nesting of list
list()it’s a constructor which is used to convert other collection data types into list or create a new list
ex
l=list((10,20,30,40))#here we have given tuple as input to list() it converts tuple into list
6)list is mutablemeans once we create a list we can add or delete or modify the same list elements
7)we can access list elements using index (supports positive indexing and negative indexing)
l=[12,13,14,15,16]
Print(l[0])#12
Print(l[1])#13
Print(l[4])#15
8)accessing list elements using for loop
l=[12,13,14,15,16]
Ex1: for i in range(len(l)):
print(l[i])
ex2: for i in l:
print(i)
9) +(concatenation) operator and * (repetition) operators in list
Ex-1
l1=[1,2,3]
L2=[4,5,6]
print(l1+l2) # [1,2,3,4,5,6]
Ex l=[2,3,4]
Print(l*2) # [2,3,4,2,3,4]
10)membership operators in list(in and not in)
s=input("enter a value")
l=[4,"hi","how",True,4.5]
if(s in l):
print("element found")
else:
print("element not found")
11)functions in list (len(),max(),min(),sum())
Len()-is a function which is used to find how many elements are present inside the given list
12)methods in list or list operations
Python has a set of built-in methods that you can use on lists/arrays.
i.append()-#we can add only one element at the end
of the list
ii.clear()-Removes all the elements from the list
iii.copy() -Returns a copy of the list
l=[10,20,30,40,10,20,40,20]
l1=l.copy()
print(l1)
iv.count()-Returns the number of elements with the specified value
l=[10,20,30,40,10,20,40,20]
print(l.count(20))
v.extend()-Add the elements of a list (or any iterable), to the end of the current list
l=[10,20,30,40]
l.extend([2,3,4,5,6])
Print(l) #[10,20,30,40,2,3,4,5,6]
vi.index()-Returns the index of the first occurrence element with the specified value
l=[10,20,30,40,10,20,40,20]
print(l.index(10))
vii.insert()-Adds an element at the specified position
l=[10,20,30,40]
print(l)
l.insert(2,25)
print(l)
viii.pop()-Removes the element at the specified position
l=[10,20,30,40,10,20,40]
print(l)
l.pop(1)
print(l)
ix.remove()-Removes the first item with the specified value
l=[10,20,30,40,10,20,40]
print(l)
l.remove(20)
print(l)
x.reverse()-Reverses the order of the list
l=[23,12,24,34]
l.reverse()
print(l)
xi.sort()-Sorts the list in ascending order
l=[23,12,24,34]
l.sort()
print(l)
ex-2
l=[23,12,24,34]
l.sort()
print(l)
l.reverse()
print(l)
13)working with nested list
l=[[1,2,3],[4,5,6],[7,8,9]]
for i in l:
for j in i:
print(j,end="")
print("")
3.Define String? Explain about Strings?
STRINGS
1. Defination:- string is collection of characters enclosed in single quotes(‘ ‘) or double quotes(“ “) or single triple
quotes(‘ ‘ ‘ welcome ‘ ‘ ‘) or double triple quotes (“””welcome”””)
single line strings
multi line strings
2. characters may be alphabets or digits or special symbols or white space or combination of all
Ex: “abc”,”123”,”[email protected]”, “#insta”,”welcome to vision computers”
3. assigning string to a variable
S=“welcome”
len() function is an inbuilt function in Python programming language that returns the length of the
string.
string is index based collection- Strings are ordered sequences of character data. Indexing allows you to
access individual characters in a string directly by using a numeric value. String indexing is zero-based: the
first character in the string has index 0, the next is 1, and so on
4. string supports both positive indexing and negative indexing-Each character can be accessed using their index
number.
To access characters in a string we have two ways:
Positive index number
Negative index number
In Python Positive indexing, we pass a positive index that we want to access in square brackets. The index
number starts from 0 which denotes the first character of a string.
In negative indexing in Python, we pass the negative index which we want to access in square brackets.
Here, the index number starts from index number -1 which denotes the last character of a string.
# b is of type float
b = 10.10
print("\nType before : ", type(b))
# type of c is list
c = [1, 2, 3]
print("\nType before :", type(c))
14) slicing in strings is the technique of getting sub string from the given string
For slicing in strings we take the support of index
Syntax
string[start:end:step]
You can return a range of characters by using the slice syntax.
by default step is 1 if we don’t give any thing
example
b = "Hello, World!"
print(b[2:5])
print
output
llo
example 2:
String ='ASTRING'
# Using indexing sequence
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
# Prints string in reverse
print("\nReverse String")
print(String[::-1])
output
AST
SR
GITA
Reverse String
GNIRTSA
4.What are Data types in Python? Explain them with examples?
Python Data Types
Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not
need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
Example:
a=5
The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret
variables a as an integer type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function,
which returns the type of the variable passed.
example to define the values of different data types and checking its type.
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be integer, floating
number or even complex numbers. These values are defined as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole numbers (without fraction
or decimal). In Python there is no limit to how long an integer value can be.
Float – This value is represented by float class. It is a real number with floating point representation. It is
specified by a decimal point. Optionally, the character e or E followed by a positive or negative integer may be
appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified as (real part) + (imaginary
part)j. For example – 2+3j
Example:
File:
Input:
# Python program to demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
Boolean
Boolean type provides two built-in values, True and False. These values are used to determine the given statement
true or false. It denotes by the class bool. True can be represented by any non-zero value or 'T' whereas false can be
represented by the 0 or 'F'. Consider the following example.
Example:
File:
Input:
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows to store multiple
values in an organized and efficient fashion. There are several sequence types in Python –
String
List
Tuple
1) String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more
characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character
is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Example:
File:
Input:
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
2) List
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very flexible as the
items in a list do not need to be of the same type.
Creating List
However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and
enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator
(*) works with the list in the same way as they were working with the strings.
Example:
File:
Input:
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
3) Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it is created. It is represented by tuple class. A tuple is a
read-only data structure as we can't modify the size and value of the items of a tuple.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ (,) with or without the use of
parentheses () for grouping of the data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the parentheses is
not sufficient, there must be a trailing ‘comma’ to make it a tuple.
Example:
File:
Input:
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
# Tuple slicing
print (tup[1:])
print (tup[0:1])
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.
Creating Dictionary
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Example:
File:
Input:
Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
1st name is Jimmy
2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate elements. The
order of elements in a set is undefined though it may consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the sequence
inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same, various mixed-up data
type values can also be passed to the set.
Example:
File:
Input:
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
Output:
Initial blank Set:
set()
1)print( ) function
The print() function prints the specified message to the screen or another standard output device.
The message that wants to print can be a string or any other object. This function converts the object into a string
before written to the screen.
Example 1: Print a string onto the screen:
print("welcome to JKC")
Output:
• welcome to JKC
Example 2: Print more than one object onto the screen:
print("Analytics Vidhya", "Chirag Goyal", "Data Scientist", "Machine Learning")
Output:
Analytics Vidhya Chirag Goyal Data Scientist Machine Learning
2)type( ) function
The type() function returns the type of the specified object.
Example 1: Return the type of the following object:
list_of_fruits = ('apple', 'banana', 'cherry', 'mango')
print(type(list_of_fruits))
Output:
<class 'tuple'>
Example 2: Return the type of the following objects:
variable_1 = "Analytics Vidhya"
variable_2 = 105
print(type(variable_1))
print(type(variable_2))
Output:
<class 'str'>
<class 'int'>
type( ) function
The type() function returns the type of the specified object.
Example 1: Return the type of the following object:
list_of_fruits = ('apple', 'banana', 'cherry', 'mango')
print(type(list_of_fruits))
Output:
<class 'tuple'>
Example 2: Return the type of the following objects:
variable_1 = "Analytics Vidhya"
variable_2 = 105
print(type(variable_1))
print(type(variable_2))
Output:
<class 'str'>
<class 'int'>
3)input( ) function
The input() function allows taking the input from the user.
Example: Use the prompt parameter to write the complete message after giving the input:
a = input('Enter your name:')
print('Hello, ' + a + ' to Analytics Vidhya')
Output:
Enter your name:Chirag Goyal
Hello, Chirag Goyal to Analytics Vidhya
4)abs( ) function
The abs() function returns the absolute value of the specified number.
Example 1: Return the absolute value of a negative number:
negative_number = -676
print(abs(negative_number))
Output:
676
Example 2: Return the absolute value of a complex number:
complex_number = 3+5j
print(abs(complex_number))
Output:
5.830951894845301
5) pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.
If a third parameter is present in this function, then it returns x to the power of y, modulus z.
Example 1: Return the value of 3 to the power of 4:
x = pow(3, 4)
print(x)
Output:
81
Example 2: Return the value of 3 to the power of 4, modulus 5 (same as (3 * 3 * 3 * 3) % 5):
x = pow(3, 4, 5)
print(x)
Output:
7) sorted( ) function :
The sorted() function returns a sorted list of the specified iterable object.
You can specify the order to be either ascending or descending. In this function, Strings are sorted alphabetically,
and numbers are sorted numerically.
NOTE: If a list contains BOTH string values AND numeric values, then we cannot sort it.
Example 1: Sort the specified tuple in ascending order:
tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple))
Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Example 2: Sort the specified tuple in descending order:
tuple = ("h", "b", "a", "c", "f", "d", "e", "g")
print(sorted(tuple, reverse=True))
Output:
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
8) max( ) function
The max() function returns the item with the maximum value or the item with the maximum value in an iterable.
If the values this function takes are strings, then it is done using an alphabetical comparison.
Example 1: Return the name with the highest value, ordered alphabetically:
names_tuple = ('Chirag', 'Kshitiz', 'Dinesh', 'Kartik')
print(max(names_tuple))
Output:
Kshitiz
Example 2: Return the item in a tuple with the highest value:
number_tuple = (2785, 545, -987, 1239, 453)
print(max(number_tuple))
Output:
2785
9) round( ) function
The round() function returns a floating-point number that is a rounded version of the specified number, with the
specified number of decimals.
The default number of decimals is 0, meaning that the function will return the nearest integer.
Example 1: Round the specified positive number to the nearest integer:
nearest_number = round(87.76432)
print(nearest_number)
Output:
88
Example 2: Round the specified negative number to the nearest integer:
nearest_number = round(-87.76432)
print(nearest_number)
Output:
-88
Example 3: Round the specified number to the nearest integer:
nearest_number = round(87.46432)
print(nearest_number)
Output:
87