SlideShare a Scribd company logo
1 of 25
Download to read offline
Flow Control
if, else, elif, while, break,
continue, for
Ranjana Thakuria
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru
1
Flow Control Statements
 if Statement
 else Statements
 elif Statements
 while Loop Statements
 break Statements
 continue Statements
 for Loops and the range() Function
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru
2
if else Statement
if Statement :
 The most common type of flow control statement is the if statement.
 An if statement’s clause (that is, the block following the if statement)
will execute if the statement’s condition is True.
 The clause is skipped if the condition is False.
else Statements
 An if clause can optionally be followed by an else statement.
 The else clause is executed only when the if statement’s condition is
False.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru
3
if statement consists
 The if keyword
 A condition (that is, an expression that evaluates to True or False)
 A colon(:)
 Starting on the next line, an indented block of code (called the if clause)
else statement consists
 The else keyword
 A colon
 Starting on the next line, an indented block of code (called the else
clause)
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 4
If Example:
if name == 'Alice’:
print('Hi, Alice.')
Flowchart:
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 5
If –else Example:
if name == 'Alice’:
print('Hi, Alice.')
else:
print('Hello, stranger.')
Flowchart:
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 6
Rules for blocks
There are three rules for blocks.
1. Blocks begin when the
indentation increases.
2. Blocks can contain other
blocks.
3. Blocks end when the
indentation decreases to zero or to
a containing block’s indentation.
Example:
if name == 'Mary’:
print('Hello Mary')
if password == 'swordfish’:
print('Access granted.')
else:
print('Wrong password.')
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 7
while Loop Statements
• You can make a block of code execute over
and over again with a while statement.
• The code in a while clause will be executed
as long as the while statement’s condition is
True.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 8
A while statement always consists:
• The while keyword
• A condition (that is, an expression that evaluates
to True or False)
• A colon
• Starting on the next line, an indented block of
code (called the while clause)
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 9
Example- while:
spam = 0
while spam < 5:
print('Hello, world.’)
spam = spam + 1
Flowchart
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 10
break Statements
 • ‘Break’ in Python is a loop control statement.
• There is a shortcut to getting the program execution to
break out of a while loop’s clause early.
• If the execution reaches a break statement, it immediately
exits the while loop’s clause.
• break statement is put inside the loop body (generally
after if condition).
• In code, a break statement simply contains the break
keyword.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 11
Example- break:
while True:
print('Please type your
name.’)
name = input()
if name == 'your name’:
break
print('Thank you!')
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 12
continue Statements
 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.
 When the program execution reaches a continue statement,
the program execution immediately jumps back to the start
of the loop and re-evaluates the loop’s condition.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 13
Example- continue :
Flowchart
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 14
for Loops and the range() Function
 To execute a block of code only a certain number of
times
 It uses for loop statement and the range() function
together
 Eg. for i in range(5):
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru
15
for always includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three
integers passed to it
• A colon
• Starting on the next line, an indented block of
code (called the for clause)
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 16
Example:
 # display your name five times:
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 17
Example 1:
The Starting, Stopping, and Stepping Arguments to range()-
for i in range(12, 16):
print(i)
Explanation:
*The first argument will be where the for loop’s variable
starts.
*The second argument will be up to, but not including, the
number to stop at.
 Output:
12
13
14
15
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 18
Example 1:
The Starting, Stopping, and Stepping Arguments to range()-
for i in range(0, 10, 2):
print(i)
:
• The range() function can also be called with three
arguments.
• The first two arguments will be the start and stop
values, and the third will be the step argument.
• The step is the amount that the variable is increased by
after each iteration.
 Output:
0
2
4
6
8
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 19
Example 3:
for i in range(5, -1, -1):
print(i)
Explanation:
The 3rd arguments to range() function
is -1.So backward propagation can be
achieved.
 Output:
5
4
3
2
1
0
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 20
Importing Modules
• All Python programs can call a basic set of functions called built-in
functions, including the print(), input(), and len() functions.
• Python also comes with a set of modules called the standard library.
• Each module is a Python program that contains a related group of functions
that can be embedded in your programs.
• For example, the math module has mathematics- related functions.
• The random module has random number–related functions, and so on.
• Before you can use the functions in a module, you must import the module
with an import statement.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 21
An import statement consists of the
following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they
are separated by commas
• Once you import a module, you can use all the
functions of that module.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 22
Example : import
1)
import random for i in range(5):
print(random.randint(1, 10))
Note:
The random.randint() is a
function call.
randint() is function name which
is present in the random module.
2)
import random, sys, os, math
3) An alternative form of the import
statement
from random import *
Note:
composed of the from keyword,
followed by the module name, the
import keyword, and a star;
With this form of import statement,
calls to functions in random will not
need the random. prefix.
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 23
Ending a Program early with sys.exit()
• This can cause the program to terminate, or exit, by calling the
sys.exit() function.
• Since this function is in the sys module, you have to import sys before
your program can use it.
Example: import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.')
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 24
Bibliography:
1. Al Sweigart,“Automate the Boring Stuff with Python”,1 stEdition, No Starch Press, 2015. (Available
under CC-BY-NC-SA license at https://automatetheboringstuff.com/) (Chapters 1 to 18, except 12) for
lambda functions use this link: https://www.learnbyexample.org/python-lambda-function/
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2 nd Edition, Green Tea
Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf (Chapters 13, 15, 16, 17, 18) (Download
pdf/html files from the above link)
3. Introduction to Python Programming - 22PLC15B/25B (Module 1) notes Prepared by, Mrs. Divyaraj G
N, Assistant Professor, CSE, SVCE, Bengaluru
Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 25

More Related Content

Similar to ch2 Python flow control.pdf

While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in collegessuser7a7cd61
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfdata2businessinsight
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in PythonDrJasmineBeulahG
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
control statements
control statementscontrol statements
control statementsAzeem Sultan
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3Isham Rashik
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation fileRujanTimsina1
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSAniruddha Paul
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 

Similar to ch2 Python flow control.pdf (20)

Chap04
Chap04Chap04
Chap04
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 
130706266060138191
130706266060138191130706266060138191
130706266060138191
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Exception Handling in Python
Exception Handling in PythonException Handling in Python
Exception Handling in Python
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
control statements
control statementscontrol statements
control statements
 
Java loops
Java loopsJava loops
Java loops
 
Android Application Development - Level 3
Android Application Development - Level 3Android Application Development - Level 3
Android Application Development - Level 3
 
ch5.ppt
ch5.pptch5.ppt
ch5.ppt
 
Python session3
Python session3Python session3
Python session3
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Python basics
Python basicsPython basics
Python basics
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Python Programming Basics
Python Programming BasicsPython Programming Basics
Python Programming Basics
 
PYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMSPYTHON FULL TUTORIAL WITH PROGRAMMS
PYTHON FULL TUTORIAL WITH PROGRAMMS
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 

ch2 Python flow control.pdf

  • 1. Flow Control if, else, elif, while, break, continue, for Ranjana Thakuria Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 1
  • 2. Flow Control Statements  if Statement  else Statements  elif Statements  while Loop Statements  break Statements  continue Statements  for Loops and the range() Function Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 2
  • 3. if else Statement if Statement :  The most common type of flow control statement is the if statement.  An if statement’s clause (that is, the block following the if statement) will execute if the statement’s condition is True.  The clause is skipped if the condition is False. else Statements  An if clause can optionally be followed by an else statement.  The else clause is executed only when the if statement’s condition is False. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 3
  • 4. if statement consists  The if keyword  A condition (that is, an expression that evaluates to True or False)  A colon(:)  Starting on the next line, an indented block of code (called the if clause) else statement consists  The else keyword  A colon  Starting on the next line, an indented block of code (called the else clause) Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 4
  • 5. If Example: if name == 'Alice’: print('Hi, Alice.') Flowchart: Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 5
  • 6. If –else Example: if name == 'Alice’: print('Hi, Alice.') else: print('Hello, stranger.') Flowchart: Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 6
  • 7. Rules for blocks There are three rules for blocks. 1. Blocks begin when the indentation increases. 2. Blocks can contain other blocks. 3. Blocks end when the indentation decreases to zero or to a containing block’s indentation. Example: if name == 'Mary’: print('Hello Mary') if password == 'swordfish’: print('Access granted.') else: print('Wrong password.') Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 7
  • 8. while Loop Statements • You can make a block of code execute over and over again with a while statement. • The code in a while clause will be executed as long as the while statement’s condition is True. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 8
  • 9. A while statement always consists: • The while keyword • A condition (that is, an expression that evaluates to True or False) • A colon • Starting on the next line, an indented block of code (called the while clause) Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 9
  • 10. Example- while: spam = 0 while spam < 5: print('Hello, world.’) spam = spam + 1 Flowchart Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 10
  • 11. break Statements  • ‘Break’ in Python is a loop control statement. • There is a shortcut to getting the program execution to break out of a while loop’s clause early. • If the execution reaches a break statement, it immediately exits the while loop’s clause. • break statement is put inside the loop body (generally after if condition). • In code, a break statement simply contains the break keyword. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 11
  • 12. Example- break: while True: print('Please type your name.’) name = input() if name == 'your name’: break print('Thank you!') Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 12
  • 13. continue Statements  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.  When the program execution reaches a continue statement, the program execution immediately jumps back to the start of the loop and re-evaluates the loop’s condition. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 13
  • 14. Example- continue : Flowchart Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 14
  • 15. for Loops and the range() Function  To execute a block of code only a certain number of times  It uses for loop statement and the range() function together  Eg. for i in range(5): Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 15
  • 16. for always includes the following: • The for keyword • A variable name • The in keyword • A call to the range() method with up to three integers passed to it • A colon • Starting on the next line, an indented block of code (called the for clause) Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 16
  • 17. Example:  # display your name five times: print('My name is') for i in range(5): print('Jimmy Five Times (' + str(i) + ')') Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 17
  • 18. Example 1: The Starting, Stopping, and Stepping Arguments to range()- for i in range(12, 16): print(i) Explanation: *The first argument will be where the for loop’s variable starts. *The second argument will be up to, but not including, the number to stop at.  Output: 12 13 14 15 Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 18
  • 19. Example 1: The Starting, Stopping, and Stepping Arguments to range()- for i in range(0, 10, 2): print(i) : • The range() function can also be called with three arguments. • The first two arguments will be the start and stop values, and the third will be the step argument. • The step is the amount that the variable is increased by after each iteration.  Output: 0 2 4 6 8 Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 19
  • 20. Example 3: for i in range(5, -1, -1): print(i) Explanation: The 3rd arguments to range() function is -1.So backward propagation can be achieved.  Output: 5 4 3 2 1 0 Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 20
  • 21. Importing Modules • All Python programs can call a basic set of functions called built-in functions, including the print(), input(), and len() functions. • Python also comes with a set of modules called the standard library. • Each module is a Python program that contains a related group of functions that can be embedded in your programs. • For example, the math module has mathematics- related functions. • The random module has random number–related functions, and so on. • Before you can use the functions in a module, you must import the module with an import statement. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 21
  • 22. An import statement consists of the following: • The import keyword • The name of the module • Optionally, more module names, as long as they are separated by commas • Once you import a module, you can use all the functions of that module. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 22
  • 23. Example : import 1) import random for i in range(5): print(random.randint(1, 10)) Note: The random.randint() is a function call. randint() is function name which is present in the random module. 2) import random, sys, os, math 3) An alternative form of the import statement from random import * Note: composed of the from keyword, followed by the module name, the import keyword, and a star; With this form of import statement, calls to functions in random will not need the random. prefix. Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 23
  • 24. Ending a Program early with sys.exit() • This can cause the program to terminate, or exit, by calling the sys.exit() function. • Since this function is in the sys module, you have to import sys before your program can use it. Example: import sys while True: print('Type exit to exit.') response = input() if response == 'exit': sys.exit() print('You typed ' + response + '.') Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 24
  • 25. Bibliography: 1. Al Sweigart,“Automate the Boring Stuff with Python”,1 stEdition, No Starch Press, 2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/) (Chapters 1 to 18, except 12) for lambda functions use this link: https://www.learnbyexample.org/python-lambda-function/ 2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2 nd Edition, Green Tea Press, 2015. (Available under CC-BY-NC license at http://greenteapress.com/thinkpython2/thinkpython2.pdf (Chapters 13, 15, 16, 17, 18) (Download pdf/html files from the above link) 3. Introduction to Python Programming - 22PLC15B/25B (Module 1) notes Prepared by, Mrs. Divyaraj G N, Assistant Professor, CSE, SVCE, Bengaluru Ranjana Thakuria, Astt. Prof, CSE, SVCE, Bengaluru 25