Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

Python Programming

UNIT 2
Python Operators

Operators are used to perform operations on


variables and values.

Python divides the operators in the following groups:


1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Identity operators
6. Membership operators
7. Bitwise operators
Python Operators
1- Python Arithmetic Operators - Arithmetic operators are used with
numeric values to perform common mathematical operations:

OPERATOR Name Example

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y
2- Python Assignment Operators - Assignment operators are used to assign
values to variables:
OPERATOR Example Same as
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
3- Python Comparison Operators - Comparison operators are used to
compare two values:

OPERATOR Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


4- Python Logical Operators - Logical operators are used to combine
conditional statements:

OPERATOR Description Example

and Returns True if both x < 5 and x < 10


statements are true

or Returns True if one of x < 5 or x < 4


the statements is true

not Reverse the result, not(x < 5 and x < 10)


returns False if the
result is true
5- Python Identity Operators - Identity operators are used to compare the
objects, not if they are equal, but if they are actually the same object, with the
same memory location:

OPERATOR Description Example

is Returns True if both x is y


variables are the same
object

is not Returns True if both x is not y


variables are not the
same object
6- Python Membership Operators - Membership operators are
used to test if a sequence is presented in an object:

OPERATOR Description Example


in Returns True if a x in y
sequence with the
specified value is
present in the object
not in Returns True if a x not in y
sequence with the
specified value is not
present in the object
7- Python Bitwise Operators - Bitwise operators are used to compare
(binary) numbers:

OPERATOR Name Description

& AND Sets each bit to 1 if both bits


are 1

| OR Sets each bit to 1 if one of two


bits is 1

^ XOR Sets each bit to 1 if only one of


two bits is 1

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in


from the right and let the
leftmost bits fall off

>> Signed right shift Shift right by pushing copies of


the leftmost bit in from the left,
and let the rightmost bits fall
off
Python Control Statements

We have three control statements in Python:

1. Continue : With the continue statement we can stop


the current iteration of the loop, and continue with
the next:

2. Break: With the break statement we can stop the loop


before it has looped through all the items:

3. Pass: for loops cannot be empty, but if you for some


reason have a for loop with no content, put in
the pass statement to avoid getting an error.
Python Conditional Statements

Conditional Statements: Conditional Statement in Python perform


different computations or actions depending on whether a specific Boolean
constraint evaluates to true or false. Conditional statements are handled by
IF statements in Python.

Python if Statement is used for decision-making operations. It contains a


body of code which runs only when the condition given in the if statement
is true. If the condition is false, then the optional else statement runs which
contains some code for the else condition.

Python if Statement Syntax:


if expression :
Statement
else :
Statement
Python Statements
Python Looping Statements
For Loop

A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).

 With the for loop we can execute a set of statements, once for each item
in a list, tuple, set etc

Example:
for x in "banana":
print(x)

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter.

Syntax:

FOR x in range():
Stmts
Python Looping Statements
Python while Loop Statements

A while loop statement in Python programming language repeatedly


executes a target statement as long as a given condition is true.

Syntax
The syntax of a while loop in Python programming language is −

while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The
loop iterates while the condition is true.
Python Data Structures
Python Lists
The list is a most versatile data structure available in Python which can be written as
a list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.

Creating a list is as simple as putting different comma-separated values between


square brackets.
For example −
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]

Example –
thislist = ["apple", "banana", "cherry"]
print(thislist)

Properties of LIST ITEM:-


List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Python Data Structures
Basic List Operations
Lists respond to the + and * operators much like strings; they mean
concatenation and repetition here too, except that the result is a new list,
not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: 123 Iteration


print x,
Python Data Structures
Built-in List Functions & Methods
.
Sr.N Function with Description
o.

1 cmp(list1, list2) Compares elements of both lists.

2 len(list) Gives the total length of the list.

3 max(list) Returns item from the list with max value.

4 min(list) Returns item from the list with min value.

5 list(seq) Converts a tuple into list.


Python includes following list methods

Sr.No. Methods with Description

1 list.append(obj)Appends object obj to list

2 list.count(obj)Returns count of how many times obj occurs in list

3 list.extend(seq)Appends the contents of seq to list

4 list.index(obj)Returns the lowest index in list that obj appears

5 list.insert(index, obj)Inserts object obj into list at offset index

6 list.pop(obj=list[-1])Removes and returns last object or obj from list

7 list.remove(obj)Removes object obj from list

8 list.reverse()Reverses objects of list in place

9 list.sort([func])Sorts objects of list, use compare func if given


Accessing Values in Lists

To access values in lists, use the square brackets for slicing along
with the index or indices to obtain value available at that index.

For example −
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0]
print "list2[1:5]: ", list2[1:5]

Output-
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists

You can update single or multiple elements of lists by giving the slice on
the left-hand side of the assignment operator, and you can add to
elements in a list with the append() method.

For example

list = ['physics', 'chemistry', 1997, 2000]


print "Value available at index 2 : “
print list[2]
list[2] = 2001;
print "New value available at index 2 : "
print list[2]

When the above code is executed, it produces the following result −


Value available at index 2 : 1997
New value available at index 2 : 2001
Delete List Elements

To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting or the remove() method if
you do not know.

For example −

list1 = ['physics', 'chemistry', 1997, 2000]


print list1
del list1[2]
print "After deleting value at index 2 : "
print list1

When the above code is executed, it produces following result −


['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
Python Data Structures

Python – Tuples
A tuple is a collection of objects which ordered and immutable.
Tuples are sequences, just like lists. The differences between tuples
and lists are, the tuples cannot be changed unlike lists and tuples
use parentheses, whereas lists use square brackets.

EXAMPLE-
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Properties of TUPLE ITEMS:-

Tuple items are ordered, unchangeable, and allow duplicate values.


Tuple items are indexed, the first item has index [0], the second
item has index [1] etc.
Creating a tuple

A tuple can be written as the collection of comma-separated (,) values


enclosed with the small () brackets. The parentheses are optional but
it is good practice to use. A tuple can be defined as follows.
T1 = (101, "Peter", 22)
T2 = ("Apple", "Banana", "Orange")
T3 = 10,20,30,40,50

print(type(T1))
print(type(T2))
print(type(T3))
Creating a tuple with single element is slightly different.
We will need to put comma after the element to declare
the tuple.

1.tup1 = (“Python")
2.print(type(tup1))
3.#Creating a tuple with single element
4.tup2 = (“Python",)
5.print(type(tup2))

Output:
<class 'str'>
<class 'tuple'>
Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the
index or indices to obtain value available at that index.

For example −
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]

When the above code is executed, it produces the following result −


tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Tuple indexing and slicing

The indexing and slicing in the tuple are similar to lists. The indexing in the
tuple starts from 0 and goes to length(tuple) - 1.
The items in the tuple can be accessed by using the index [] operator. Python
also allows us to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Negative Indexing
The tuple element can also access by using negative indexing.
The index of -1 denotes the rightmost element and -2 to the second
last item and so on.
The elements from left to right are traversed using the negative
indexing.

Consider the following example:


1.tuple1 = (1, 2, 3, 4, 5)
2.print(tuple1[-1])
3.print(tuple1[-4])
4.print(tuple1[-3:-1])
5.print(tuple1[:-1])
6.print(tuple1[-2:])

Output:
5 2 (3, 4) (1, 2, 3, 4) (4, 5)
Deleting Tuple

Unlike lists, the tuple items cannot be deleted by using


the del keyword as tuples are immutable. To delete an entire tuple,
we can use the del keyword with the tuple name.

Consider the following example.

tuple1 = (1, 2, 3, 4, 5, 6)
print(tuple1)
del tuple1[0]
print(tuple1)
del tuple1
print(tuple1)
Basic Tuple operations
The operators like concatenation (+), repetition (*), Membership (in)
works in the same way as they work with the list. Consider the following
table for more detail.
Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example

Repetition The repetition operator enables the T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)


tuple elements to be repeated
multiple times.

Concatenation It concatenates the tuple T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)


mentioned on either side of the
operator.

Membership It returns true if a particular item print (2 in T1) prints True.


exists in the tuple otherwise false

Iteration The for loop is used to iterate over for i in T1: print(i)Output1 2 3 4 5
the tuple elements.

Length It is used to get the length of the len(T1) = 5


tuple.
Python Tuple inbuilt functions

SN Function Description

1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1


is greater than tuple2 otherwise false.

2 len(tuple) It calculates the length of the tuple.

3 max(tuple) It returns the maximum element of the tuple

4 min(tuple) It returns the minimum element of the tuple.

5 tuple(seq) It converts the specified sequence to the tuple.


List vs. Tuple
SN List Tuple

1
The literal syntax of list is shown The literal syntax of the tuple is
by the []. shown by the ().
2
The List is mutable. The tuple is immutable.

3
The List has the a variable length. The tuple has the fixed length.

4
The list provides more The tuple provides less functionality
functionality than a tuple. than the list.
5
The list is used in the scenario in The tuple is used in the cases
which we need to store the where we need to store the read-
simple collections with no only collections i.e., the value of the
constraints where the value of items cannot be changed. It can be
the items can be changed. used as the key inside the
dictionary.
6
The lists are less memory The tuples are more memory
efficient than a tuple. efficient because of its immutability.
Python Data Structures
Python Set
1. A Python set is the collection of the unordered items.
2. Each element in the set must be unique, immutable, and the sets
remove the duplicate elements.
3. Sets are mutable which means we can modify it after its creation.
4. Unlike other collections in Python, there is no index attached to the
elements of the set, i.e., we cannot directly access any element of the set
by the index.
5. However, we can print them all together, or we can get the list of
elements by looping through the set.

EXAMPLE-
thisset = {"apple", "banana", "cherry“}
print(thisset)

Properties of SET ITEMS:-


Set items are unordered, unchangeable, and do not allow duplicate values.
Creating sets

Example 1: Using curly braces

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",


"Sunday"}
print(Days)
print(type(Days))

Example 2: Using set() method

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturd


ay", "Sunday"])
print(Days)
print(type(Days))
Adding items to the set

Python provides the add() method and update() method which can be used
to add some particular item to the set. The add() method is used to add a
single element whereas the update() method is used to add multiple
elements to the set.

Example: 1 - Using add() method

Months = set(["January","February", "March", "April", "May", "June"])


print("\nprinting the original set ... ")
print(months)
print("\nAdding other months to the set...");
Months.add("July");
Months.add ("August");
print("\nPrinting the modified set...");
print(Months)
Example - 2 Using update() function

Months = set(["January","February", "March", "April", "Ma


y", "June"])
print("\nprinting the original set ... ")
print(Months)
print("\nupdating the original set ... ")
Months.update(["July","August","September","October"]);

print("\nprinting the modified set ... ")


print(Months);
Removing items from the set
Python provides the discard() method and remove() method which can be used
to remove the items from the set. The difference between these function, using
discard() function if the item does not exist in the set then the set remain
unchanged whereas remove() method will through an error.
Example-1 Using discard() method
months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.discard("January");
months.discard("May");
print("\nPrinting the modified set...");
print(months)

Example-2 Using remove() function


months = set(["January","February", "March", "April", "May", "June"])
print("\nprinting the original set ... ")
print(months)
print("\nRemoving some months from the set...");
months.remove("January");
months.remove("May");
print("\nPrinting the modified set...");
print(months)
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with
the sets by using which we can check whether a set is a subset, superset, or
equivalent to other set. The boolean true or false is returned depending upon
the items present inside the sets.

Consider the following example.

Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}


Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}

#Days1 is the superset of Days2 hence it will print true.


print (Days1>Days2)

#prints false since Days1 is not the subset of Days2


print (Days1<Days2)

#prints false since Days2 and Days3 are not equivalent


print (Days2 == Days3)
Python Built-in set methods
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the item is already present
in the set.
2 clear() It deletes all the items from the set.
3 copy() It returns a shallow copy of the set.
4 difference_update(....) It modifies this set by removing all the items that are also present in the
specified sets.
5 discard(item) It removes the specified item from the set.
6 intersection() It returns a new set that contains only the common elements of both the
sets. (all the sets if more than two are specified).

7 intersection_update(....) It removes the items from the original set that are not present in both
the sets (all the sets if more than one are specified).

8 Isdisjoint(....) Return True if two sets have a null intersection.


9 Issubset(....) Report whether another set contains this set.
10 Issuperset(....) Report whether this set contains another set.
11 pop() Remove and return an arbitrary set element that is the last element of
the set. Raises KeyError if the set is empty.

12 remove(item) Remove an element from a set; it must be a member. If the element is


not a member, raise a KeyError.

13 symmetric_difference(....) Remove an element from a set; it must be a member. If the element is


not a member, raise a KeyError.

14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and another.
15 union(....) Return the union of sets as a new set.
(i.e. all elements that are in either set.)
16 update() Update a set with the union of itself and others
Python Dictionary

Python Dictionary is used to store the data in a key-value pair format.

The dictionary is the data type in Python, which can simulate the real-life data
arrangement where some specific value exists for some particular key.

 It is the mutable data-structure.

The dictionary is defined into element Keys and values.

Keys must be a single element.

Value can be any type such as list, tuple, integer, etc.

In other words, we can say that a dictionary is the collection of key-value pairs
where the value can be any Python object.

In contrast, the keys are the immutable Python object, i.e., Numbers, string, or
tuple.
EXAMPLE 1-
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)

Example2-

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}


print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Accessing the dictionary values

1.Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOG


LE"}
2.print(type(Employee))
3.print("printing Employee data .... ")
4.print("Name : %s" %Employee["Name"])
5.print("Age : %d" %Employee["Age"])
6.print("Salary : %d" %Employee["salary"])
7.print("Company : %s" %Employee["Company"])

Output:
<class 'dict'>
printing Employee data ....
Name : John
Age : 29
Salary : 25000
Company : GOOGLE
Built-in Dictionary functions

SN Function Description

1 cmp(dict1, dict2) It compares the items of both the


dictionary and returns true if the first
dictionary values are greater than the
second dictionary, otherwise it returns
false.

2 len(dict) It is used to calculate the length of the


dictionary.

3 str(dict) It converts the dictionary into the


printable string representation.

4 type(variable) It is used to print the type of the passed


variable.
Built-in Dictionary methods
SN Method Description

1 dic.clear() It is used to delete all the items of the dictionary.


2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, Create a new dictionary from the iterable with the values
value = None, /) equal to value.
4 dict.get(key, default = It is used to get the value specified for the passed key.
"None")
5 dict.has_key(key) It returns true if the dictionary contains the specified
key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= It is used to set the key to the default value if the key is
"None") not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value pair of
dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len()
12 popItem()
13 pop()
14 count()
15 index()
Python Functions:

Function is a block of code or set of statements that performs a specific task


and executes only when called. Complex projects can be broken down into
smaller tasks.

Syntax:
def function-name():

Example:
def palindrome():

In the above syntax:

def - to declare/define the function


function-name- name of the function
() - required to distinguish between a variable and function and end the
definition with a semi-colon
Example
def greet():
print("Hello")
print("Im a student")

greet()
Using the above function you can print the greet message multiple times by just
calling the function multiple times instead of making the code redundant with
print lines.

There are two basic types of Functions:


1) Built-in Functions
2) User Defined Functions

Built-in Functions:
Built-in functions are part of Python language. These are the functions readily
available for the use.

max() - Returns the largest item in an iterable.


min() - Returns the smallest item in an iterable.
input() -To accept the input from the user
User defined functions :
User defined functions are not in-built and are not a part of Python
programming language

Function

def sub(x,y):
diff=x-y Prints the difference between two
print(diff) numbers

sub(7,4)

Functions can return values:


def add(x,y):
c=x+y
return c
result=add(5,4)
print(result)

Output: 9
In the above example, the value returned by the function stores in the
variable "result" and the desired output is printed on the console
Function returning two values:

A function can return two values in a similar way as the first one, but two variables have
to be initialized to store the two values returned by the function after computation.
Example
def add_sub(x,y):
c=x+y
d=x-y;
return c,d

result1,result2=add_sub(5,4)
print(result1,result2)

Function Arguments
Arguments are used to feed information to the functions i.e to pass the information. Any
number of arguments can be passed. They are declared inside the parenthesis after the
function name.
Example:
def add(x,y):
c=x+y
print(c)
add(5,4)

In the above code, the variables x and y are Formal arguments and
numbers 5,4 are Actual Arguments
Types of Function Arguments:

1) Position Arguments
2) Keyword Arguments
3) Default Arguments
4) Variable Length Arguments
5) Keyworded Variable Length Argument

Position Arguments
Positional Arguments are the arguments passed in a positional/sequential
order. The number of arguments passed should match the function definition. If
the arguments are passed in a non-sequential order, then function computation
will throw an error.
Example:

def student(name,age):
print(name)
print(age)

student('paul',28)

Output: paul
28
Keyword Arguments

Keyword Arguments are used in the function call which passes the arguments
along with a keyword. This facilitates the user to pass the arguments in a non
positional order.If the sequence of the arguments is not known, keyword
arguments can be used in a function call.

Example:

def student(name,age):
print(name)
print(age)

student(age=28,name='paul')

Output: paul
28

Default Arguments:

It's a type of argument which assumes a default value if a particular value is not
mentioned in the function call. If a user doesn't provide a particular argument
the default value in the function definition will be assigned autonomously to the
that particular argument.
Variable Length Arguments

Variable Arguments are the arguments used in the function calls when a
function has to compute more arguments than the arguments in the function
definition or when the accurate value of arguments is not known. They are
named with an asterisk before the variable-name that holds multiple or non
keyword arguments.

Example:

def sum(a,*b): c=a;


for i in b:
c=c+i
print(c)

sum(5,6,34,78)

Output: 123

Key worded Variable Length Arguments:

Key worded Variable Arguments are the arguments with a special syntax
**kwargs in function definitions in python is used to pass a key
worded,variable-length argument list.
Example:
def myname(**b):
for key, value in b.items():
print ("%s == %s" %(key, value))

myname(first ='John', mid ='Mathew', last='roy')

Output: last == John


mid == Mathew
first == roy

Recursion
Recursion is a process of calling a function from the same function repeatedly.
It means a defined function can call itself. It reduces the complexity of a
program.

Example: Factorial using Recursion


def fact(n):
if n==0:
return 1
return n*fact(n-1)
result=fact(5)
print(result)
Output: 120
Lambda or Anonymous Function

As the name suggests, these are the functions without any name. It's a kind of
function, which is not defined in an usual manner with def. Lamba function
returns only a single value. It can accept any number of arguments. It has to be
assigned to a variable.

Example 1:

f = lambda a: a+a
result=f(5)
print(result)

Output: 10

Example 2:

g = lambda b,c: b-c


result1=g(6,5)
print(result1)

Output: 1

You might also like