0% found this document useful (0 votes)
6 views

Python PPT UNIT-2

The document provides an overview of Python control structures, including conditionals, loops, and jumping statements. It explains the use of lists, their properties, and common functions and methods associated with them. Additionally, it covers built-in functions like any(), all(), enumerate(), and operator functions for performing various operations.

Uploaded by

mrimpatient04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Python PPT UNIT-2

The document provides an overview of Python control structures, including conditionals, loops, and jumping statements. It explains the use of lists, their properties, and common functions and methods associated with them. Additionally, it covers built-in functions like any(), all(), enumerate(), and operator functions for performing various operations.

Uploaded by

mrimpatient04
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Python Control

Structures

1
Conditionals
 In Python, True and False are Boolean objects of class 'bool' and they are
immutable.
 Python assumes any non-zero and non-null values as True, otherwise it is False
value.
 Python does not provide switch or case statements as in other languages.
 Syntax:
if Statement if..else Statement if..elif..else
Statement
 Exampl
e:

2
Conditionals

 Using the conditional expression


Another type of conditional structure in Python, which is very convenient and easy to
read.

3
Loops
 The For
Loop

 The while
Loop

4
Jumping Statement
 break :Terminates the statement and executio to the
loop
immediately following the transfers n statement
loop.

 continue :Causes the loop to skip the remainder of its body and immediately retest
its
condition prior to reiterating.

 pass :Used when a statement is required syntactically but you do not want
any command or code to execute.

5
Random Number
• Python does not have a random() function to make a
random number, but Python has a built-in module called
random that can be used to make random numbers:
• Example
Import the random module, and display a random number
between 1 and 9:

import random
print(random.randrange(1, 10))
6
Range() Function
• Returns a sequence of numbers, starting from 0 by default, and increments by
1 (by default), and stops before a specified number.
• Syntax
range(start, stop, step)
• Example:
x = range(3, 6)
for n in x:
print(n)
O/P:
3
4
5 7
Range()
• Create a sequence of numbers from 3 to 19, but increment by 2
instead of 1:
• x = range(3, 20, 2)
for n in x:
print(n)

8
Sequence
• The most basic data structure in Python is the sequence.
• Each element of a sequence is assigned a number - its position or
index.
• The first index is zero, the second index is one, and so forth.
• Python has six built-in types of sequences, but the most common
ones are lists and tuples.
• There are certain things you can do with all the sequence types.
• These operations include:
 Indexing, slicing, adding, multiplying, and checking for
membership.
• In addition, Python has built-in functions for finding the length of a
sequence and for finding its largest and smallest elements.

9
Lists
 A list in Python is an ordered group of items or elements, and these list elements
don't have to be of the same type.
 Python Lists are mutable objects that can change their values.
 A list contains items separated by commas and enclosed within square brackets.
 List indexes like strings starting at 0 in the beginning of the list and working their way
from -1 at the end.
 Similar to strings, Lists operations include slicing ([ ] and [:]) , concatenation (+),
repetition (*), and membership (in).
 This example shows how to access, update and delete list elements:

 access
 slice
 update

 delete

10
List
Examples of list:
list1 = ['physics', 'chemistry', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];

Indexing, Slicing and Matrixes


Since lists are sequences, indexing and slicing work the same way for
lists as they do for strings.
Assuming the following input-
L=['C++'', 'Java', 'Python']

11
Lists
 Lists can have sublists as elements and these sublists may contain other
sublists
as well.

 Common List
Functions

12
Lists
Function Description
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(tuple) Converts a tuple into list.

 Common List
Methods
Method Description
list.append(obj) Appends object obj to list
list.insert(index, obj) Inserts object obj into list at offset index
list.count(obj) Returns count of how many times obj occurs in list
list.index(obj) Returns the lowest index in list that obj appears
list.remove(obj) Removes object obj from list
list.reverse() Reverses objects of list in place
list.sort() Sorts objects of list in place 13
Lists

 List Comprehensions
Each list comprehension consists of an expression followed by a for
clause.

 List comprehension

14
any()
• The any() method returns True if any element of an iterable is True. If not, any() returns False.
• syntax :
any(iterable)
iterable (list, string, dictionary etc.)
• any() returns:
True if at least one element of an iterable is true
False if all elements are false or if an iterable is empty
When Return Value

All values are true True

All values are false False

One value is true (others are false) True

One value is false (others are true) True

Empty Iterable False

15
Example (any())
• l = [1, 3, 4, 0]
• print(any(l))
True
• l = [0, False] False
• print(any(l))
True
• l = [0, False, 5]

False
print(any(l))

• l = []
• print(any(l))

16
all()
• The all() method returns True when all elements in the given iterable are true. If not, it returns False
• syntax :
all(iterable)
iterable (list, string, dictionary etc.)
• any() returns:
True if all element of an iterable is true
False if any elements in an iterable is false
Truth table for all()

When Return Value

All values are true True

All values are false False

One value is true (others are false) False

One value is false (others are true) False

Empty Iterable True


17
Example (all())
• # all values true
• l = [1, 3, 4, 5]
• print(all(l))
• # all values false True
• l = [0, False]
• print(all(l)) False
• # one false value


l = [1, 3, 4, 0]
print(all(l))
False


# one true value
l = [0, False, 5]
False
• print(all(l)) True
• # empty iterable
• l = []
• print(all(l))

18
enumerate()
• The enumerate() method adds counter to an iterable and returns it (the enumerate object).
• syntax:
– enumerate(iterable, start=0)
 iterable - a sequence, an iterator, or objects that supports iteration
 start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start.
• The returned object is a enumerate object.You can convert enumerate objects to list and tuple using
list() and tuple() method respectively.

grocery = ['bread', 'milk', 'butter']


enumerateGrocery = enumerate(grocery)
print(type(enumerateGrocery))
<class 'enumerate’>
# converting to list
[(0, 'bread'), (1, 'milk'), (2, 'butter’)]
print(list(enumerateGrocery))
[(10, 'bread'), (11, 'milk'), (12, 'butter')]
# changing the default counter
enumerateGrocery = enumerate(grocery, 10)
19
print(list(enumerateGrocery))
accumulate()
• This iterator takes two arguments, iterable target and the function which would be followed at
each iteration of value in target. If no function is passed, addition takes place by default. If the
input iterable is empty, the output iterable will also be empty.
• Must import the itertools module before using.
• We have to also import the operator module because we want to work with operators.
• Syntax
itertools.accumulate(iterable[, func]) –> accumulate object
• This function makes an iterator that returns the results of a function.

import itertools operator.mul(1, 2)


import operator
1 2
GFG = [1, 2, 3, 4, 5] 2 operator.mul(2, 3)
result = itertools.accumulate(GFG, operator.mul) 6 6
for each in result: 24 operator.mul(6, 4)
print(each) 120 24
operator.mul(24, 5)
120 20
enumerate()
import itertools 5 5
import operator 5 max(5, 3)
GFG = [5, 3, 6, 2, 1, 9, 1] 6 5
result = itertools.accumulate(GFG, max) 6 max(5, 6)
for each in result: 6 6
print(each) 9 max(6, 2)
9 6
max(6, 1)
6
max(6, 9)
9
max(9, 1)
9

21
Operator Functions in Python
Python has predefined functions for many mathematical, logical, relational, bitwise etc operations under
the module “operator”. Some of the basic functions are covered in this article.
1. add(a, b) :- This functions returns addition of the given arguments.
Operation – a + b.
2. sub(a, b) :- This functions returns difference of the given arguments.
Operation – a – b.
3. mul(a, b) :- This functions returns product of the given arguments.
Operation – a * b.
4. truediv(a,b) :- This functions returns division of the given arguments.
Operation – a / b.
5. floordiv(a,b) :- This functions also returns division of the given arguments. But the value is floored
value i.e. returns greatest small integer.
Operation – a // b.
6. pow(a,b) :- This functions returns exponentiation of the given arguments.
Operation – a ** b.
7. mod(a,b) :- This functions returns modulus of the given arguments.
Operation – a %a b.

22
Operator Functions in Python
import operator The addition of numbers is :7
a=4 The difference of numbers is :1
b=3 The product of numbers is :12
print ("The addition of numbers is :",end="");
print (operator.add(a, b))
print ("The difference of numbers is :",end="");
print (operator.sub(a, b))
print ("The product of numbers is :",end="");
print (operator.mul(a, b))

23
Sort()
• sort() method doesn't return any value. Rather, it changes the
original list.
• If you want the original list, use sorted().
• Example:
vowels = ['e', 'a', 'u', 'o', 'i’]

# sort the vowels

vowels.sort()

# print vowels

print('Sorted list:', vowels)


• O/P: Sorted list: ['a', 'e', 'i', 'o', ‘u’]
• To sort in Descending order:
list.sort(reverse=True)

24
Sort using your own function with key parameter
• sort() also accepts a key function as an optional parameter.
• Based on the results of the key function, you can sort the given list.
list.sort(key=len)
• len is the Python's in-built function to count the length of an element.
• The list is sorted based on the length of its each element, from lowest count to highest.

def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
random.sort(key=takeSecond)
# print list
print('Sorted list:', random)
25
Output: Sorted list: [(4, 1), (2, 2), (1, 3), (3, 4)]
Sorted()
• The sorted() function sorts the elements of a given iterable in a specific
order (either ascending or descending) and returns the sorted iterable as a
list.
• The syntax of the sorted() function is:
– sorted(iterable, key=None, reverse=False)
• iterable - A sequence (string, tuple, list) or collection (set, dictionary, frozen
set) or any other iterator.
• reverse (Optional) - If True, the sorted list is reversed (or sorted in
descending order). Defaults to False if not provided.
• key (Optional) - A function that serves as a key for the sort comparison.
Defaults to None.

26
Example of sorted()
• py_list = ['e', 'a', 'u', 'o', 'i']
• print(sorted(py_list)) ['a', 'e', 'i', 'o', 'u’]
['P', 'h', 'n', 'o', 't', 'y’]
['a', 'e', 'i', 'o', 'u’]
• # string
• py_string = 'Python'
• print(sorted(py_string))

• # vowels tuple
• py_tuple = ('e', 'a', 'u', 'o', 'i')
• print(sorted(py_tuple))

• py_string = 'Python'
• print(sorted(py_string, reverse=True))
27

You might also like