Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Python (Part 2)

Uploaded by

lalit.saini2060
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python (Part 2)

Uploaded by

lalit.saini2060
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Python

(Part-2)

National Institute of Electronics and Information Technology


NIELIT, Gorakhpur
Control Statements

• Control statements decides the direction of flow of


program execution.

• Decision making:
– if statement
– if...else statement
– if…elif…else statement
The if statement
• It is used to execute one or more statement
depending upon whether condition is true or
not.
• Syntax:-
num=1
if condition: if num==1:
statements print(‘one’)
Indentation
• In Python, the body of the if statement is indicated by the
indentation. Body starts with an indentation and the first
unindented line marks the end.
• It refers to spaces that are used in the beginning of a statement.
The statements with same indentation belong to same group called
a suite.
• By default, Python uses 4 spaces but it can be increased or
decreased by the programmers.
if x==1:
print(‘a’)
print(‘b’)
If y==2:
print(‘c’)
print(‘d’)
print(‘end’)
print (‘’end)
The if…else Statement
• The if..else statement evaluates test expression and
will execute body of if only when test condition is
True. If the condition is False, body of else is
executed. Indentation is used to separate the blocks.

• Syntax:- Example:

If condition: num = 3
Satement1 if num >= 0:
print("Positive or Zero")
else: else:
Statement2 print("Negative number")
if...elif...else Statement

• The elif is short for else if. It allows us to check for


multiple expressions.
• If the condition for if is False, it checks the condition of the
next elif block and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is
executed according to the condition.
• The if block can have only one else block. But it can have
multiple elif blocks.
Syntax:

if condition1: Example:
Statement1 num = 3.4
if num > 0:
elif condition2: print("Positive number")
Statement2 elif num == 0:
print("Zero")
elif condition3: else:
Statement3 print("Negative number")

else:
Body of else
Problems
• WAP to input the number and check it is even or odd.
• WAP to check a number is positive or negative.
• WAP to check greatest among two numbers.
• WAP to check a year leap year or not.
• WAP to check greatest among three numbers.
• WAP to check a three digit number is palindrome or not.
• WAP to input the cost price and selling price of an item
and check for profit or loss. Also calculate it.
The While loop
• The while loop is used to iterate over a block of code as
long as the test expression (condition) is true.
• Syntax:
while condition:
Body of while
• Working:
In while loop, test expression is checked first. The body
of the loop is entered only if the condition evaluates to
True. After one iteration, the test expression is checked
again. This process continues until the condition
evaluates to False.
• The body of the while loop is determined through
indentation.
Flow Chart: Example:

Output:
while loop with else

• We can also use an optional else block with while


loop.
• The else part is executed if the condition in the while
loop evaluates to False.
Example: Output:
The For Loop
• The for loop is used to iterate (repeat) over a sequence (list,
tuple, string) or other iterable objects. Iterating over a
sequence is called traversal.
• Syntax:
for val in sequence:
Body of for

(val is the variable that takes the value of the item inside the
sequence on each iteration)
• Loop continues until we reach the last item in the sequence.
The body of for loop is separated from the rest of the code
using indentation.
Flow Chart:
Example:

Output:
range() function

• It is used to provide a sequence of numbers.


• range(n) gives numbers from 0 to n-1.
• For example, range(10) returns numbers from 0
to 9.
• For example, range(5, 10) returns numbers from 5
to 9.
• We can also define the start, stop and step size as
range(start, stop, step size), step size defaults to
1 if not provided.
• Step size represents the increment in the value of
the variable at each step.
Example: Output:

Example: Output:
for loop with else

• A for loop can have an optional else block. The else


part is executed if the items in the sequence used in
for loop exhausts.
• break statement can be used to stop the loop. In
such case, the else part is ignored.
• Hence, a for loop's else part runs if no break occurs.
Example: Output:
break and continue

• break and continue statements can alter the flow of


a normal loop.
break statement:-
• The break statement terminates the loop containing
it. Control of the program flows to the statement
immediately after the body of the loop.
• If break statement is inside a nested loop (loop inside
another loop), break will terminate the innermost
loop.
• Syntax :-
break
Flow Chart: Working:
• The continue statement is used to skip the rest
of the code inside a loop for the current
iteration only. Loop does not terminate but
continues on with the next iteration.
Pass

• The pass statement does not do anything.


• It is used with ‘if’ statement or inside a loop to represent no
operation.
• Use pass statement when we need a statement syntactically
but we do not want to do any operation

Ex:
for i in range(10):
if i%2==0:
pass
else:
print(i)
print(‘end of loop’)
Python List
• In Python programming, a list is created by placing all the
items (elements) inside a square bracket [ ], separated by
commas.
• It can have any number of items and they may be of different
types (integer, float, string etc.).
• # empty list
my_list = []
• # list of integers
my_list = [1, 2, 3]
• # list with mixed datatypes
my_list = [1, "Hello", 3.4]
• # nested list
my_list = ["mouse", [8, 4, 6], ['a']]
Accessing List Elements?

• List Index
The for loop in Python is used to iterate over a sequence (list, tuple, string) or
other iterable objects. Iterating over a sequence is called traversal.

Syntax of for Loop

for val in sequence:


Body of for

Here, val is the variable that takes the value of the item
inside the sequence on each iteration.

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]


# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
# Output: The sum is 48
print("The sum is", sum)
The range() function

• We can generate a sequence of numbers using range()


function. range(10) will generate numbers from 0 to 9
(10 numbers).
• We can also define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not
provided.
• This function does not store all the values in memory, it
would be inefficient. So it remembers the start, stop,
step size and generates the next number on the go.
• To force this function to output all the items, we can use
the function list().
• # Output: range(0, 10)
print(range(10))
• # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(range(10)))
• # Output: [2, 3, 4, 5, 6, 7]
print(list(range(2, 8)))
• # Output: [2, 5, 8, 11, 14, 17]
print(list(range(2, 20, 3)))
Array
• An array is an object that stores a group of elements
(or values) of same datatype.
• The size of the array is not fixed in python. Hence,
we need not specify how many elements we are
going to store into an array in the beginning.
• Arrays can grow or shrink in memory dynamically
(during runtime).
• Creating an Array:
arrayname=array(type code, [elements])
a=array(‘i’, [4,6,2]) -integer type array
arr= array(‘d’,[1.5,-2.2,3,5.75]) -double type array
Importing the Array Module
• import array
a= array.array(‘i’,[4,6,2,9])
• Import array as ar
a=ar.array(‘i’,[4,6,2,9])
• from array import*
a=array(‘i’,[4,6,2,9])
(* symbol represents all)
Example: Output:
Indexing and Slicing on Arrays
• An index represents the position number of an
element in an array. For example, the
following integer type array:
X=array(‘i’, [10, 20, 30, 40, 50])
10 20 30 40 50

X[0] X[1] X[2] X[3] X[4]

Allocates 5 blocks of memory each of 2 bytes of size and


stores the elements 10, 20, 30, 40, 50.
Example: Output:

The len(a) function returns the number of elements in the array ‘a’ into n.
Type Codes to Create Array
Example: Output:
#Accessing array elements

#Slicing Arrays
Change or add elements in the array

We can add one item to a list using append() method or add several items
using extend() method.
Insert at particular location

Example:

Output:
Remove/delete elements

We can delete one or more items from an array using Python's del statement.

Example: Output:

We can use the remove() method to remove the given item, and pop() method to
remove an item at the given index.
Problems:

1. WAP to store student’s marks (60,70,75,45 and 50) into an


array and find total marks and percentage of marks.
2. Take an array of elements 5,10,15,20,25,30,35,40,45,50
and perform the following operations:
a) Print the 3rd and 5th element.
b) Slice the array into two arrays from 0 to 3 and 5
onwards.
c) Change the element of 4th position by element 32
d) Delete the 6th element
e) Insert a new element 55 at last position of the array.
f) Delete the element 40 from the array.
g) Extend the array by elements 60,65,70 and 75.
h) Insert a new element 18 at 4th position of the array.
3. Program to search for the position of an element in an array.

You might also like