SlideShare a Scribd company logo
1 of 28
Download to read offline
Python Decision Making
And Loops
Decision making
● Decision making is the most important aspect of almost all the
programming languages.
● Decision structures evaluate multiple logical expressions which produce
TRUE or FALSE as outcome.
● non-zero and non-null values as TRUE, otherwise FALSE
Decision making
Decision making statements in python
1. If
2. If else
3. nested if
Indentation in Python
● For the ease of programming and to achieve simplicity, python doesn't allow
the use of parentheses for the block level code.
● In Python, indentation is used to declare a block.
● If two statements are at the same indentation level, then they are the part of
the same block.
● Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.
The if statement
The syntax of the if-statement is given below.
if expression:
statement
E.g.
a=10
if a :
print(“ value is ”,a)
or
a=10
if a : print(“ value is ”,a)
The if statement
e.g. X= int(input(“Enter a number”))
r=X%2
if (r==0):
print(“Even”)
print(“Bye”)
o/p:
Enter a number : 3
bye
Enter a number : 50
Even
Bye
The if-else statement
The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.
If the condition is true, then the if-block is executed.
Otherwise, the else-block is executed.
The if-else statement
Syntax:
if expression:
statement(s)
else :
statement(s)
The if-else statement
age = int (input("Enter your age? "))
if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! You are not eligible to vote !!");
The elif statement
● The elif statement enables us to check multiple conditions and execute the
specific block of statements depending upon the true condition among them.
● We can have any number of elif statements in our program depending upon
our need.
● However, using elif is optional.
● The elif statement works like an if-else-if ladder statement in C. It must be
succeeded by an if statement.
The elif statement
Nested if
• Can use one if or else if statement inside another if or else if statement(s).
• Can have an if...elif...else construct inside another if...elif...else construct.
LOOPS
● Allows us to execute a statement or group of statements multiple times.
1. While loop
2. For loop
3. Nested loop
while loop
● Repeatedly executes target statement(s) as long as a given condition is true
Syntax: while condition:
statement(s)
● Python uses indentation as its method of grouping statements
● In Python, all the statements indented by the same number of character
spaces after a programming construct( if, for , while etc….) are considered to
be part of a single block of code
● While loop needs,
counter variable
condition
increment or decrement
● Infinite loop – Cntl + C
while loop
i=1
number = int(input("Enter the number:"))
while i<=10:
print("%d X %d = %d n" %(number,i,number*i))
i = i+1
Output:
1
2
3
4
5
6
7
8
9
10
While with Else
● Python supports to have an else statement
associated with a loop statement.
● If the else statement is used with a while
loop, the else statement is executed when
the condition becomes false.
●
Print a message once the condition is false:
i = 0
while i < 5:
print("%d is less than 5" %i)
i += 1
else:
print("%d is not less than 5" %i)
Output
Python for loop
The for loop in Python is used to iterate the statements or a part of the program
several times.
It is frequently used to traverse the data structures like list, tuple, or dictionary.
➔ The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)
Python for loop
Example-1: Iterating string using for
loop
str = "Python"
for i in str:
print(i)
Output
P
y
t
h
o
n
Python for loop
Program to print the table of the given number .
list = [1,2,3,4,5,6,7,8,9,10]
n = 5
for i in list:
c = n*i
print(c)
For loop Using range() function
The range() function is used to generate the sequence of the numbers.
If we pass the range(10), it will generate the numbers from 0 to 9. The syntax of the
range() function is given below.
Syntax:
range(start,stop,step size)
● The start represents the beginning of the iteration.
● The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
● The step size is used to skip the specific numbers from the iteration. It is optional
to use. By default, the step size is 1. It is optional.
For loop Using range() function
Program to print numbers in sequence.
for i in range(10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
For loop Using range() function
Program to print table of given number.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
For loop Using range() function
Program to print even number using step size in
range().
n = int(input("Enter the number "))
for i in range(2,n,2):
print(i)
Output:
Enter the number 20
2
4
6
8
10
12
14
16
18
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop.
The inner loop is executed n number of times for every iteration of the outer loop.
The syntax is given below.
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
Nested for loop in python
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(1,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:
Enter the rows:5
*
**
***
****
*****
Using else statement with for loop
● Unlike other languages like C, C++, or Java, Python allows us to use the else
statement with the for loop which can be executed only when all the iterations
are exhausted.
● Here, we must notice that if the loop contains any of the break statement then
the else statement will not be executed.
Using else statement with for loop
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
Output :
0
1
2
3
4
for loop completely exhausted, since there is no break.

More Related Content

What's hot

What's hot (20)

Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
 
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
 
Linked list
Linked listLinked list
Linked list
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 
Python set
Python setPython set
Python set
 
Lists
ListsLists
Lists
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Basic blocks and control flow graphs
Basic blocks and control flow graphsBasic blocks and control flow graphs
Basic blocks and control flow graphs
 
Stack and Queue
Stack and Queue Stack and Queue
Stack and Queue
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
sparse matrix in data structure
sparse matrix in data structuresparse matrix in data structure
sparse matrix in data structure
 
stack & queue
stack & queuestack & queue
stack & queue
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 

Similar to Python Decision Making And Loops.pdf

Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1Devashish Kumar
 
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
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on SessionDharmesh Tank
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 
Looping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxLooping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxadihartanto7
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfKosmikTech1
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming LanguageDipankar Achinta
 
controlstatementspy.docx
controlstatementspy.docxcontrolstatementspy.docx
controlstatementspy.docxmanohar25689
 
Chapter 9 Conditional and Iterative Statements.pptx
Chapter 9 Conditional and Iterative Statements.pptxChapter 9 Conditional and Iterative Statements.pptx
Chapter 9 Conditional and Iterative Statements.pptxXhelalSpahiu
 

Similar to Python Decision Making And Loops.pdf (20)

Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
Introduction to Python Part-1
Introduction to Python Part-1Introduction to Python Part-1
Introduction to Python Part-1
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
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
 
gdscpython.pdf
gdscpython.pdfgdscpython.pdf
gdscpython.pdf
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
INTERNSHIP REPORT.docx
 INTERNSHIP REPORT.docx INTERNSHIP REPORT.docx
INTERNSHIP REPORT.docx
 
Chapter08.pptx
Chapter08.pptxChapter08.pptx
Chapter08.pptx
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Python Loop
Python LoopPython Loop
Python Loop
 
Looping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptxLooping in PythonLab8 lecture slides.pptx
Looping in PythonLab8 lecture slides.pptx
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdfpython-online&offline-training-in-kphb-hyderabad (1) (1).pdf
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
controlstatementspy.docx
controlstatementspy.docxcontrolstatementspy.docx
controlstatementspy.docx
 
Chapter 9 Conditional and Iterative Statements.pptx
Chapter 9 Conditional and Iterative Statements.pptxChapter 9 Conditional and Iterative Statements.pptx
Chapter 9 Conditional and Iterative Statements.pptx
 

Recently uploaded

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 

Recently uploaded (20)

Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 

Python Decision Making And Loops.pdf

  • 2. Decision making ● Decision making is the most important aspect of almost all the programming languages. ● Decision structures evaluate multiple logical expressions which produce TRUE or FALSE as outcome. ● non-zero and non-null values as TRUE, otherwise FALSE
  • 3. Decision making Decision making statements in python 1. If 2. If else 3. nested if
  • 4. Indentation in Python ● For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the block level code. ● In Python, indentation is used to declare a block. ● If two statements are at the same indentation level, then they are the part of the same block. ● Generally, four spaces are given to indent the statements which are a typical amount of indentation in python.
  • 5. The if statement The syntax of the if-statement is given below. if expression: statement E.g. a=10 if a : print(“ value is ”,a) or a=10 if a : print(“ value is ”,a)
  • 6. The if statement e.g. X= int(input(“Enter a number”)) r=X%2 if (r==0): print(“Even”) print(“Bye”) o/p: Enter a number : 3 bye Enter a number : 50 Even Bye
  • 7. The if-else statement The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition. If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
  • 8. The if-else statement Syntax: if expression: statement(s) else : statement(s)
  • 9. The if-else statement age = int (input("Enter your age? ")) if age>=18: print("You are eligible to vote !!"); else: print("Sorry! You are not eligible to vote !!");
  • 10. The elif statement ● The elif statement enables us to check multiple conditions and execute the specific block of statements depending upon the true condition among them. ● We can have any number of elif statements in our program depending upon our need. ● However, using elif is optional. ● The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if statement.
  • 12. Nested if • Can use one if or else if statement inside another if or else if statement(s). • Can have an if...elif...else construct inside another if...elif...else construct.
  • 13. LOOPS ● Allows us to execute a statement or group of statements multiple times. 1. While loop 2. For loop 3. Nested loop
  • 14. while loop ● Repeatedly executes target statement(s) as long as a given condition is true Syntax: while condition: statement(s) ● Python uses indentation as its method of grouping statements
  • 15. ● In Python, all the statements indented by the same number of character spaces after a programming construct( if, for , while etc….) are considered to be part of a single block of code ● While loop needs, counter variable condition increment or decrement ● Infinite loop – Cntl + C
  • 16. while loop i=1 number = int(input("Enter the number:")) while i<=10: print("%d X %d = %d n" %(number,i,number*i)) i = i+1 Output: 1 2 3 4 5 6 7 8 9 10
  • 17. While with Else ● Python supports to have an else statement associated with a loop statement. ● If the else statement is used with a while loop, the else statement is executed when the condition becomes false. ● Print a message once the condition is false: i = 0 while i < 5: print("%d is less than 5" %i) i += 1 else: print("%d is not less than 5" %i) Output
  • 18. Python for loop The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently used to traverse the data structures like list, tuple, or dictionary. ➔ The syntax of for loop in python is given below. for iterating_var in sequence: statement(s)
  • 19. Python for loop Example-1: Iterating string using for loop str = "Python" for i in str: print(i) Output P y t h o n
  • 20. Python for loop Program to print the table of the given number . list = [1,2,3,4,5,6,7,8,9,10] n = 5 for i in list: c = n*i print(c)
  • 21. For loop Using range() function The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is given below. Syntax: range(start,stop,step size) ● The start represents the beginning of the iteration. ● The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1 to 4 iterations. It is optional. ● The step size is used to skip the specific numbers from the iteration. It is optional to use. By default, the step size is 1. It is optional.
  • 22. For loop Using range() function Program to print numbers in sequence. for i in range(10): print(i,end = ' ') Output: 0 1 2 3 4 5 6 7 8 9
  • 23. For loop Using range() function Program to print table of given number. n = int(input("Enter the number ")) for i in range(1,11): c = n*i print(n,"*",i,"=",c)
  • 24. For loop Using range() function Program to print even number using step size in range(). n = int(input("Enter the number ")) for i in range(2,n,2): print(i) Output: Enter the number 20 2 4 6 8 10 12 14 16 18
  • 25. Nested for loop in python Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below. Syntax for iterating_var1 in sequence: #outer loop for iterating_var2 in sequence: #inner loop #block of statements #Other statements
  • 26. Nested for loop in python # User input for number of rows rows = int(input("Enter the rows:")) # Outer loop will print number of rows for i in range(1,rows+1): # Inner loop will print number of Astrisk for j in range(i): print("*",end = '') print() Output: Enter the rows:5 * ** *** **** *****
  • 27. Using else statement with for loop ● Unlike other languages like C, C++, or Java, Python allows us to use the else statement with the for loop which can be executed only when all the iterations are exhausted. ● Here, we must notice that if the loop contains any of the break statement then the else statement will not be executed.
  • 28. Using else statement with for loop for i in range(0,5): print(i) else: print("for loop completely exhausted, since there is no break.") Output : 0 1 2 3 4 for loop completely exhausted, since there is no break.