SlideShare a Scribd company logo
Rahul Kumar
CS Deptt. KIET
rahul.kumar@kiet.edu
Conditional statement
Bibek Kumar-Assistant Professor-CSE,
KIET
If, elif, else statement
Bibek Kumar-Assistant Professor-CSE,
KIET
if Statements in Python allows us to tell the computer to perform alternative actions based on a
certain set of results.
Verbally, we can imagine we are telling the computer:
"Hey if this case happens, perform some action"
We can then expand the idea further with elif and else statements, which allow us to tell the
computer:
"Hey if this case happens, perform some action. Else, if another case happens, perform some other
action. Else, if none of the above cases happened, perform this action."
if case1:
perform action1
elif case2:
perform
action2
else:
perform
action3
Syntax
If the condition "condition_1" is True, the statements of the block
statement_block_1 will be executed. If not, condition_2 will be
evaluated. If condition_2 evaluates to True, statement_block_2 will
be executed, if condition_2 is False, the other conditions of the
following elif conditions will be checked, and finally if none of them
has been evaluated to True, the indented block below the else
keyword will be executed.
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
The while statement in Python is one of most general ways to perform
iteration. A while statement will repeatedly execute a single statement or
group of statements as long as the condition is true. The reason it is called a
'loop' is because the code statements are looped through over and over
again until the condition is no longer met.
while test:
code statements
else:
final code statements
Syntax
Notice how many times the print statements
occurred and how the while loop kept going until
the True condition was met, which occurred once
x==10. It's important to note that once this
occurred the code stopped.
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
Tuples are 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 val in "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']
for i in range(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 i in 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)))
pass statement
•In Python programming, pass is a null statement.
•The difference between a comment and pass statement in Python is that,
while the interpreter ignores a comment entirely, pass is not ignored.
•However, nothing happens when pass is executed. It results into no
operation (NOP).
•Suppose we have a loop or a function that is not implemented yet, but we
want to implement it in the future. They cannot have an empty body. So, we
use the pass statement to construct a body that does nothing.
•Example
sequence = {‘p’, ‘a’, ‘s’, ‘s’}
for val in sequence:
pass
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
iterable if 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.
•How to create a string?
•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 ?
•Strings are immutable.
•We cannot delete or remove characters from a string. But deleting the
string entirely is possible using the keyword del.
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)
Ad

More Related Content

Similar to PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt (20)

Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notesPython Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Loops_in_Rv1.2b
Loops_in_Rv1.2bLoops_in_Rv1.2b
Loops_in_Rv1.2b
Carlo Fanara
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
Pavan Babu .G
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
Mr. Vikram Singh Slathia
 
05 dataflow
05 dataflow05 dataflow
05 dataflow
ali Hussien
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Philip Schwarz
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
Dharmesh Tank
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
Basil Bibi
 
Notes5
Notes5Notes5
Notes5
hccit
 
Beginning Python
Beginning PythonBeginning Python
Beginning Python
Agiliq Info Solutions India Pvt Ltd
 
Python - Lecture 2
Python - Lecture 2Python - Lecture 2
Python - Lecture 2
Ravi Kiran Khareedi
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
milissaccm
 
Advanced VB: Review of the basics
Advanced VB: Review of the basicsAdvanced VB: Review of the basics
Advanced VB: Review of the basics
robertbenard
 
Python Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notesPython Revision Tour.pptx class 12 python notes
Python Revision Tour.pptx class 12 python notes
student164700
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Python For Data Science.pptx
Python For Data Science.pptxPython For Data Science.pptx
Python For Data Science.pptx
rohithprabhas1
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
Pavan Babu .G
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part 2
Philip Schwarz
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala Part 2 ...
Philip Schwarz
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
Dharmesh Tank
 
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov, Introduction to Python, Lecture2
Anton Kasyanov
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
Brixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 RecapBrixton Library Technology Initiative Week1 Recap
Brixton Library Technology Initiative Week1 Recap
Basil Bibi
 
Notes5
Notes5Notes5
Notes5
hccit
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
milissaccm
 
Advanced VB: Review of the basics
Advanced VB: Review of the basicsAdvanced VB: Review of the basics
Advanced VB: Review of the basics
robertbenard
 

Recently uploaded (20)

Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
new ppt artificial intelligence historyyy
new ppt artificial intelligence historyyynew ppt artificial intelligence historyyy
new ppt artificial intelligence historyyy
PianoPianist
 
Ad

PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt

  • 1. Rahul Kumar CS Deptt. KIET [email protected] Conditional statement Bibek Kumar-Assistant Professor-CSE, KIET
  • 2. If, elif, else statement Bibek Kumar-Assistant Professor-CSE, KIET if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results. Verbally, we can imagine we are telling the computer: "Hey if this case happens, perform some action" We can then expand the idea further with elif and else statements, which allow us to tell the computer: "Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happened, perform this action." if case1: perform action1 elif case2: perform action2 else: perform action3 Syntax If the condition "condition_1" is True, the statements of the block statement_block_1 will be executed. If not, condition_2 will be evaluated. If condition_2 evaluates to True, statement_block_2 will be executed, if condition_2 is False, the other conditions of the following elif conditions will be checked, and finally if none of them has been evaluated to True, the indented block below the else keyword will be executed.
  • 3. 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.
  • 4. While Bibek Kumar-Assistant Professor-CSE, KIET The while statement in Python is one of most general ways to perform iteration. A while statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met. while test: code statements else: final code statements Syntax Notice how many times the print statements occurred and how the while loop kept going until the True condition was met, which occurred once x==10. It's important to note that once this occurred the code stopped.
  • 5. While Loops We can also add else statement in the loop as shown When the loop completes, the else statement is read 5
  • 6. 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
  • 7. 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
  • 8. 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 Tuples are 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
  • 9. 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
  • 10. 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
  • 11. 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 val in "string": if val == "i": continue print(val) print("The end") 11
  • 12. 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)
  • 13. 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'] for i in range(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 i in range(10, 5, -1): print(i) #OutPut : 10, 9, 8, 7, 6
  • 14. 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)))
  • 15. pass statement •In Python programming, pass is a null statement. •The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored. •However, nothing happens when pass is executed. It results into no operation (NOP). •Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. So, we use the pass statement to construct a body that does nothing. •Example sequence = {‘p’, ‘a’, ‘s’, ‘s’} for val in sequence: pass
  • 16. 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
  • 17. 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
  • 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
  • 19. 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
  • 20. 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
  • 21. 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 iterable if condition = = true] Only accept items that are not apple Newlist = [x for x in fruits if x!=“apple”]
  • 22. 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. •How to create a string? •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)
  • 23. 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 ? •Strings are immutable. •We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del.
  • 24. 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")
  • 25. 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()
  • 26. 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")
  • 27. 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)