Bibek Kumar-Assistant Professor-CSE,
KIET
The if, elif and else Statements
Examples
Multiple Branches
Note how the nested if statements are each checked until a True
Boolean causes the nested code below it to run. We should also
note that we can put in as many elif statements as we want
before we close off with an else.
While
Bibek Kumar-Assistant Professor-CSE,
KIET
ThewhilestatementinPythonisoneofmostgeneralwaystoperform
iteration.Awhilestatementwillrepeatedlyexecuteasinglestatementor
groupofstatementsaslongastheconditionistrue.Thereasonitiscalleda
'loop'isbecausethecodestatementsareloopedthroughoverandover
againuntiltheconditionisnolongermet.
while test:
code statements
else:
final code statements
Syntax
Noticehowmanytimestheprintstatements
occurredandhowthewhileloopkeptgoinguntil
theTrueconditionwasmet,whichoccurredonce
x==10.It'simportanttonotethatoncethis
occurredthecodestopped.
While Loops
We can also add else statement in the loop as shown
When the loop completes, the else statement is read.
5
While Loops
We can use break, continue, and pass statements in our loops to add additional functionality for
various cases. The three statements are defined by:
•break: Breaks out of the current closest enclosing loop.
•continue: Goes to the top of the closest enclosing loop.
•pass: Does nothing at all.
Syntax:
while test:
code
statement
if test:
break
if test:
continue
else:
break and continue statements can appear anywhere inside the loop’s body, but we will usually
put them further nested in conjunction with an if statement to perform an action based on some
condition.
A word of caution however! It is possible to create an
infinitely running loop with while statements.
6
A for loop acts as an iterator in Python; it goes through items
that are in a sequence or any other iterable item. Objects that
we've learned about that we can iterate over include strings,
lists, tuples, and even built-in iterables for dictionaries, such as
keys or values.
for item in object:
statements to do
stuff
Example
Let's print only the even numbers from that list!
We could have also put an else statement in there
7
For loop
Using the for Statement
Another common idea during a for loop is keeping some sort of
running tally during multiple loops
We've used for loops with lists, how about with strings?
Remember strings are a sequence so when we iterate through
them we will be accessing each item in that string.
Let's now look at how a for loop can be used with a tuple
Tuplesare very similar to lists, however, unlike lists they are
immutable meaning they can not be changed. You would use
tuples to present things that shouldn't be changed, such as days
of the week, or dates on a calendar.
The construction of a tuples use () with elements separated by
commas.
8
Using the for Statement
Tuples have a special quality when it comes to for loops. If you
are iterating through a sequence that contains tuples, the item
can actually be the tuple itself, this is an example of tuple
unpacking. During the for loop we will be unpacking the tuple
inside of a sequence and we can access the individual items
inside that tuple!
Iterating through Dictionaries
9
Break statement
•Used to terminate the execution of the nearest enclosing loop .
•It is widely used with for and while loop
Example
I = 1
while I <= 10:
print(I, end=“ “)
if I==5:
break
I = I+1
Print (“Out from while loop”)
10
Continue statement
•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.
Example
for valin "string":
if val== "i":
continue
print(val)
print("The end")
11
Range() function
12
The range() is an in-built function in Python. It returns a sequence of
numbers starting from zero and increment by 1 by default and stops
before the given number.
x = range(5)
for n in x:
print(n)
Example : range(5) will start from 0 and end at 4.
range(start, stop, step)
Range() function
13
Along with loops, range() is also used to iterate over the list types using
the len function and access the values through the index
Example
listType=['US', 'UK', 'India', 'China']
fori inrange(len(listType)):
print(listType[i])
Reverse Range
•We can give either positive or negative numbers for any of the
parameters in the range.
•This feature offers the opportunity to implement reverse loops.
•We can do this by passing a higher index as a start and a negative step
value.
for iin range(10, 5, -1):
print(i) #OutPut : 10, 9, 8, 7, 6
Range() function
14
Create List, Set and Tuple using Range
range() comes handy in many situations, rather than only using to write
loops.
For example, we create List, Set, and Tuple using range function instead of
using loops to avoid boilerplate code.
Example:
print(list(range(0, 10, 2)))
print(set(range(0, 10, 2)))
print(tuple(range(0, 10, 2)))
print(list(range(10, 0, -2)))
print(tuple(range(10, 0, -2)))
Lambda OR Anonymous function
They are not declared as normal function.
They do not required def keyword but they are declared with a lambda
keyword.
Lambda function feature added to python due to
Demand from LISP programmers.
Syntax: lambda argument1,argument2,….argumentN: expression
Example:
Sum = lambda x,y: x+y
Program:
Program that passes lambda function as an argument to a function
def func(f, n):
print(f(n))
Twice = lambda x:x *2
Thrice = lambda y:y*3
func(Twice, 5)
func(Thrice,6)
Output: 10
18
Functional programming decomposes a problem into set of functions.
1.filter( )
This function is responsible to construct a list from those elements of the list
for which a function returns True.
Syntax: filter (function, sequence)
Example:
def check(x):
if(x%2==0 or x%4==0):
return 1
evens = list(check, range(2,22))
print(evens)
O/P: [2,4,6,8…….16,18,20]
Functional Programming
2. map():
It applies a particular function to every element of a list.
Its syntax is similar to filter function
After apply the specified function on the sequence the map() function
return the modified list.
map(function, sequence)
Example:
def mul_2(x):
x*=2
return x
num_list= [1,2,3,4,5,6,7]
New_list= list(map(mul_2, num_list)
Print(New_list)
Functional Programming
2. reduce():
It returns a single value generated by calling the function on the first two
items of the sequence then on result and the next item, and so on.
Syntax: reduce(function, sequence)
Example:
import functools
def add(a,b):
return x,y
num_list= [1,2,3,4,5]
print(functools.reduce(add, num_list))
Functional Programming
List comprehension offers a shorter syntax when we want to create a new list
Based on the values of an existing list.
Example
Fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [ ]
for x in Fruits:
if “a” in x:
newlist.append(x)
Print(newlist)
List Comprehension
With list comprehension it
can do with one statement
Newlist= [x for x in fruits if
“a” in x]
Syntax:
Newlist= [expression for item in
iterableif condition = = true]
Only accept items that are not
apple
Newlist= [x for x in fruits if
x!=“apple”]
Strings
•A string is a sequence of characters.
•Computers do not deal with characters, they deal with numbers (binary).
Even though you may see characters on your screen, internally it is stored
and manipulated as a combination of 0’s and 1’s.
•Howtocreateastring?
•Strings can be created by enclosing characters inside a single quote or
double quotes.
•Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.
myString = ‘Hello’
print(myString) myString = "Hello"
print(myString) myString = ‘’’Hello’’’
print(myString)
How to access characters in a string?
myString = "Hello"
#print first Character
print(myString[0])
#print last character using negative indexing
print(myString[-1])
#slicing 2nd to 5th character
print(myString[2:5])
#print reverse of string
print(myString[::-1])
How to change or delete a string ?
•Stringsareimmutable.
•Wecannotdeleteorremovecharactersfromastring.Butdeletingthe
stringentirelyispossibleusingthekeyworddel.
String Operations
•Concatenation
s1 = "Hello "
s2 = “KNMIET"
#concatenation of 2 strings
print(s1 + s2)
#repeat string n times
print(s1 * 3)
•Iterating Through String
count = 0
for l in "Hello World":
if l == "o":
count += 1
print(count, " letters found")
String Membership Test
•To check whether given character or string is present or not.
•For example-
print("l" in "Hello World")
print("or" in "Hello World")
•String Methods
•lower()
•join()
•split()
•upper()
Python Program to Check whether a String is
Palindrome or not?
myStr = "Madam"
#convert entire string to either lower or upper
myStr = myStr.lower()
#reverse string
revStr = myStr[::-1]
#check if the string is equal to its reverse
if myStr == revStr:
print("Given String is palindrome")
else:
print("Given String is not palindrome")
Python Program to Sort Words in Alphabetic Order?
myStr = "python Program to Sort words in Alphabetic Order"
#breakdown the string into list of words
words = myStr.split()
#sort the list
words.sort()
#printing Sorted words
for word in words:
print(word)