SlideShare a Scribd company logo
1 of 8
Download to read offline
UNIT 4:SCRATCH OR PYTHON (THEORY AND PRACTICAL) 3. COMPOUND STATEMENT
A compound statement represents a
group of statements executed as a unit. The compound statements
of python are written in a specific pattern as shown in example.
Conditions and >>> testl=2
>>>test2=4
testi:
Loops in Python >>>
t test2:
print (test1)
Let's Recal
Write advantages and disadvantages ofPython.
What doyou mean by interactive mode programming and scripting mode of
programming?
STATEMENTS FLOW OF CONTROL
Statementl
SEQUENCE
Sequence means the statements are being executed sequentially. This represents the
default flow of statement.
Statement2
Let's Learn At the end of this chapter, you should be able to:
Comprehend and
useconditionalstatements: if, if-else statements
dComprehend and use loop structure: for, while
Statement3
Fig. 1 Flow of Control
Condition
SELECTION
The selection constructs means the execution of statements depending upon
a condition. If condition evaluates to true. a course -of-action (a set of
statements) is followed otherwise another course-of-action (a different set of
statements) is followed.
true false
Let's Begin Statement(s)
Python provides control statements that serves to state what has to be done by the program, when and
under which condition(s). This chapter discusses conditional and looping statements in detail.
Fig. 2 Flow of
STATEMENTS false
Selection Construct
Decision
tarementsarethe instructions given to
the computer to perform any kind of action such as, data ITERATION
movement, decision making, repetitive action etc. Statements form the smallest executable unit within a The iteration construct means repetition of a set-of-statements depending
upon a condition till the time a condition is true (or false depending upon the
loop). a set-of-statements are repeated again and again until the condition
becomes false (or true).
true
Python program. Statements are
always terminated by semicolon.
Sequence
TYPES OF STATEMENTS IN PYTHON
1. EMPTY STATEMENTS
The simplest statement is the empty statement, which has nothing. In python empty statement is
po
IF STATEMENT Fig. 3 Flow of Iteration
statement. The if statement is the conditional statement in python and it follows selection constructs (decision
constructs).
2. SiMPLE STATEMENT
The simplest form of if statements tests a condition and if the condition evaluates to true, it carries out
some instructions and does nothing in case condition evaluates to false.
It is comprised within a
single logical line.
For example: Syntax:
name=input ("ert.I u! ame") # thls is a
staement
if test expression:
-
statement(s)
Here, the program evaluates the test expression and will execute statement() only if the text
expression is True.
Conditions and Loops in Python
Output:
If the text expression is False. the statement(5) is not executed.
Test
false
In Python, the body of the if statement is indicated by the indentation. Body
tarts with an indentation and the first unintended line marks the end.
Expression Python console
Console 1/A 3
true
Python interprets non-zero values as True. None and 0 are interpreted as False.
Example 1: Print a given statement if the number is positive.
Body of if [8]:
In
Python 3.7.0 Shell
In [8]: runfile("D:/python class /statementsi.py', wdir='D: /python class ')
x is less than y
File Edit Shell Debug Options Window Help
PYEhon 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte
1)) on win32 Fig. 4 Flowchart for
if Statement
2pcopyright
", "credits" or "license ()
"
for more information.
nun=3
>>> num>0:
In [9]:
print (num, "is a positive number. ")
rint("*his is àways Tntea. ")
Example 3: Program to test the divisibility of a number with another number.
3 is a positive number
this is always printed. Spyder (Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
F-ELSE STATEMENT
Editor D:python_ dass 11felse stat.py
n else statement can be combined with an if statement. An else statement contains the block of code
nat executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
The else statement is an optional statement and there could be at
nost only one else statement following if.
Syntax:
temp.Py ifelse stat.py
1
number1=int(input("enter first number: "))
2
number2=int(input(""enter second number: "))
3 remainder=number1%numberr2
4 if remainder==0:
Test False
Expression
The syntax of the if..else statement is -
print(number1, "is divisible by",number2)
if expression:
6 else:
True
statement(s)
print(number1, "is not divisible by", number2)
else:
Body of if Body ofelse
statement()
10
Example 2: Find out which is
greater Fig. 2 Flowchart for if..
Output:
Spyder (Python 3.6)
else statement
File Edit Search Source Run Debug Consoles Projects Tools View Help
IPython console
Console 1/A 3
Python 3.6.5 JAnaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64)]
Type copyright", "credits" or "license" for more information.
Editor D:python dass
_11statements1.py
{ temp.py" statements.py statementsi.py
-
1 Codin7: utf
2***
3 Created on iue Sep 18 i4:22:39 2018
IPython 6.4.0 -- An enhanced Interactive Python.
5"
In [1]: runfile( 'D:/python class /if else stat. .py', wdir='D: /python clàs ')
7 K=4
8y=5
9if(x*y):
10
print("x is less than y")
! else:
enter first number :123
enter second number: 23
print("y is greater than x"
123 is not divisible by 23
13
Conditions and Loops in Python
Computer Applica
cations
In a nested if construct. you can have an if..elif...else construct inside another if...elif...else construct.
IF-ELIF STATEMENT
ometimes a situation arises when there are several conditions. To handle such a situation. Python all
adding any number of. elif clause after an if and before an else clause.
allows Syntax:
if expressionl:
statement(s)
elif expression3: elif expression4:
statement{s)
Syntax: statement(s)
else:
ifexpressionl: elif expression2 : elifexpression3: if expression2: else: else:
statement1 statement_3 statement_5 statement_7 statements) statement() statement(s)
statement_2 statement_4 statement_6 statement_8 Example 5: Print a value depending on the given condition.
***********°°*
Spyder Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
.
Example 4: Program to input the marks of 5 subjects and display the grade.
Spyder (Python 3.6)
Editor-D:Python dass lnested f.py
Fie Edit Search Source Run Debug Consoles Projects Tools View Help
temp-Py eise zat.-py untted1.py 3 grade.py nestedif.py
1 var 16
2 if (var 200)
print ("Express ion value is less than 200")
if (var =
150)
print ("Which is 150")
elif (var = 100):
print (hich is 180")
elif (var ==
S0):
print( "uhich is 50")
elif( var < 50):
Editor - D:python dasS 11gradePY
tep-Py f elsesat.PY untrtledi.py grade.py
?subi=int(input("Enter marks of the first subject: "))
sub2-int (input("Enter marks of ihe second subject: "))
4 sub3=int(input("Enter marks of the third subject: "))
5
sub4=int(input("Enter marks of the fourth subject: "))
subS=int(input("Enter marks of the fifth subject: "))
avg=(subl+sub2+sub3+sub4+sub5) /5
S if(avg>90):
print("grade A")
telif(avg>=88 and avg<98)
11 print "Expressi0n value is less than 50")
2 else:
print (" Could not find true expression ")|
14
prirt grade )
12 elif(avg>=76 and avg<80):
13
print grade ")
14
elif(avg>=60 and avg<70)):
Output:
15 print("grade D")
16 else:
Python console
print("grade )
Console 1/A
Output: Expression value is less than 200
Which is 180
Enter manrks of the first subject: 78
In (3]:
Enter marks of the second subject: 98
Enter marks of the third subject: 95
LOOPING CONSTRUCTS
Enter marks of the fourth subject: 89 Loopsare used to repeatedly execute the same code in a program. Python provides two types of looping
Enter marks of the fifth subject: 85
constructs:
Erade While statement (condition based loop)
For statement (loop for a given number of times)
NESTED IF STATEMENT
InformationByte
There may be a situation when you want to check for another condition after a condition resoivE
true. In such a situation. you can use the nested if construct.
The iteration statements allow a setof instructions to be performed repeatedly until a certain condition is full filled. The
iteration statements are also called loops or looping statements.
252
Computer Application5
Onditions and LoopsinPy
253
RANGE) FUNCTION
What follows next is block of statement().
The statement(s) in BLOCK 1 keeps on
executing till condition in while remains True: once the
Before we start with loops, let us discuss range() function which Is used in for loop. range() fun..
generates a list and has a special sequence type. A sequence in python is a succession of values bound condition becomes False and if the else clause is written in while. then else will get executed. While loop
together by a single name. may not execute even once, if the condition evaluates to false, initially. as the condition is tested before
entering the loop.
Example 6: Print numbers 1 to 10.
Some python sequence types are: strings, list. tuples etc.
The common use of range() function are:
Spyder Python 3.6)
range(<lower limit>, <upper limit>) #both limits should be integers
File Edit Search Source Run Debug Consoles Projects Tools View Help
The function in the form range (1.u) will provide a list having values starting from l,1+1,1+2.
(u-1).
range(0,8) Editor D:python dass_11while.Py
list as[o.1.2.3,4.5.6.7] temp.py ifelse stat..py untitled1.py grade.py 3 nested f.py while.py
1 i-1
range(<lower limit>,<upper limit>,<step value>) #al values should be integers
range(l.u.5)
2 while(i <=10):
print (i),
i it1
gers
it will produce list having values as l, I+s, I+25..=u-1
range(0,10,2)
it will produce list as [O,2.4.6.8] Output:
range(5.0.-1) In [3]: runfile( 'D:/python_ class /vhile.py', wdir='D:/python_ <lass ")
list[5.4.3,2.1] 2
3
range(<number>)
it creates a list from O(zero) to <number>.
For example:
Range(5) 9
List as[o.1.2.3.4] 10
WHILE LoOP You can almost read the statement like English sentence. The first statement initialized the variable
(controlling loop) and then while evaluates the condition. which is True so the block of statements
It is a condition based loop.
written next will be executed.
Syntax:
Last statement in the block ensures that, with every execution of loop. loop control variable moves
while condition: # caondition is Boolean expression returning either True or False near to the termination point. If this does not happen then the loop will keep on executing infinitely.
STATEMENT BLOCK 1
As soon as i becomes 11, condition in while will evaluate to False and this will terminate the locop.
Telse: # optional part of while
STATEMENT BLOCK 2] NESTED WHILE LOOP
We can see that while looks like if statement. The staternent explains with keyword while foll
by a Boolean condition followed by colon (:).
Block of statement belonging to while can have another while statement, i.e., a while can contain another
ed
while.
254
Conditions and Loops in Python
255
r A P p l i c a t i o n
Example 8: Program to find the sum of all numbers stored in a list.
Example 7: Program with nested loop. Spyder (Python 3.6)
Spyder (Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help
File Edit Search Source Run Debug Consoles Projects Tools View HelpP
Editor- D:python_dass11forloop1.pPY
Cy ifelsestat..pyE untited1.py grade.py
Editor D:python dass_11nested while.py nested if.py while.py nested while.p
while.py nesi| 1# iist of.nunbers
untitled1.py grade.py nestedif.py
temp-py if
else stat..py s
2 numbers =
[6, 5, 3, 8, 4, 2, 5, 4, 11]
1 i = 1
4 # Variable tO store the sun
2j 5
Sum =
while 4:
while j < 8:
print(i, ",", i
4 i terate over the tist
8 for val in numbers:
9 sum = sum+val
LO
11
12 print(" The sum is", um)
Output: Output:
Python console
Python console
Console 1/A Console2/A Console 1/A
Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64) ]
Type "copyright", "credits" or "license" for more information.
Python 3.6.5 Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit
(AMD64)1
Type "copyright", "credits" or "license" for more information .
IPython 6.4.0 An enhanced Interactive Python.
IPython 6.4.0 -- An enhanced Interactive Python.
In [1]:
In 1: runfile( "b:/python class/nested while.py', wdir='D:/python class')
1 In [1]: runfile("D:/python_ class / for loop1.py', wdir='D:/python_ class')
The sum is 48
In [2]:
FOR LOODP NESTED FoR LooÞP
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other objects. Iterating y contain arnotherloop in
its body. This is
called nested loop. But in nested loop. the inne
e
over a sequence is called traversal. loop must terminate before the outer loop. for loop can be nested within another for loop.
Syntax:
for each item
Example 9: Nested for loop.
in sequence
for <val> in <sequence>: Spyder (Python 3.6)
Body of for File Edit Search Source Run Debug Consoles Projects Tools View Help
es
Last i
Here, val is the variable that takes the value of the item inside the
reached
sequence on each iteration. Editor D:Python class_11nested forloop-pY
No
Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
statment3.py E3
1 for outer in range (6,10,4):
for inner in range(1,outer,2):
print (outer, inner)
nested for loop-py 3
Bodyoffor
Exit loop
ig. 3 Flowchart of for Loo
Conditions and Loops in Python
256 257
o m p u t e r
Applications
i o n s
andL
cONTINUE STATEMENT
Output: Enter loop
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
n 1: runfile( D:/python lass /nested for loop.py', wdir='D:/python class")
Test
False
expression of
oop
6 3 with the next iteration.
Syntax:
True
Continue
JUMP STATEMENTSs BREAKANDCONTINUE
Yes
Python offers two jump statements to be used within loops tojump out of loop-iterations. These
break and continue statements.
s. These are Example 11: Program using continue Statement. Continue?
Spyder(Python3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
Enter loop |No
Exit
loOP
THE BREAK STATEMENT Test Remaining8
False Editor-D:python cass 11continuel.py
body ofloop
Ihe break statement terminates the loop containing it. Control of
the program flows to the statement immediately after the body of
the loop.
expression of
looP
19y gradepy nestedfpy3 while.py3 nested wnie.py PYunon.py or oop1.g
Fig. 5 Flowchart of Continue
2 for val in "string":
True 3 if val == "i":
4 continue
If break statement is inside a nested loop (loop inside another
loop). break will terminate the innermost loop.
5 print(val1)
Yes
Break? 7 print(The end")
Syntax:
No
break
Output:
Exit
loop
Remaining
bodyofloop Tn [4]: runfile( 'D: /python_ class /continue1 .Py', wdir='D: /python_ class ")
Fig. 4 Flowchart of break
Example 10:
Theend
Spyder (Python 3.6)
File Edit Search Source Run Debug Consoles Projects Tools View Help
Example 12: Program to illustrate the difference between break and continue statement.
Spyder (Python3.6)
File Edit Search Source Run Debug Consoles Projects Tools View HelpP
Editor D:python dass_1iibreaki.py
at-py untitied.Py gade.py nested f-py while.py nested while.py Pyon
1 for val in "string" : Editor-D:ythonclass_11statment3.py
if val == "i": statment3.py
break 1 #break condit ion
print(val) 2print("the loop with break statement produces output as:
3 for i in range(1,10):
if ik2==0:
6 print(The end") 4
break
B else:
print(i
8 #cont inue condtit ion
Output: 9print("the loop with continue statement produces output as: ")
18 for i in range(1,10):
In [2]: runfile( D:/python_ class (break1.py', wdir='D:/python_ class ')
if ix2==0:
12 continue
t
L3 else:
4 print(i)
The end
Computer
plication Conditions and Loops in Python
259
258
Output: Ans. Ans. it will calculate square of numbers
enter an integer3
lass/statment3.py', wdir='D:/python
class
")
In [7]: runfile( D. /python
the loop with break statement produces output as
the loop with continue statement produces output as Q4. Find the output offollowing code.
=1
*2
1= 3 Q8. Write a program to check whether given numberis
even or odd.
sum=
ANS.
number=int (input ("enter any e"))
for i in (x.y.2): number$2==0:
if (isinstancei, int): print
(number,"i an even
nher")|
Lets Summarise Sum =sum+i print (number, "1s an dd nunber ")
print fsum)
Output:
Python supports selection orconditional statements.
There are three types ofstatements in python, namely emply statements, simple statements. compound statements.
The iteration constructs mean repetition of a set-of-Stalements depending upon a condition till the time a condition is true (or
Ans. enter any nunber12
n even nunber
Q5. What gets printed?
false depending upon the loop), a set-of-statements are repeated again and again. Q9. Program to print whetlher a given character is an
if x>3:
uppercase or a lowercase character or a digit or any
other character.
A Compound statement represents a group of statements executed as a unit.
if x>4:
------~----- -----*- printA",end=" ") AnS.
character iiput"entei d
ligL cia ")
Character>*' 11d charaCter<='2':
else:
Glossary haTActe .tLacter")
charact
printB".end="*")
, .
prnt("yo 7t
charactetx"i ' ai character<'':
P a t e i r u ilg
if(x!=0):
. Endless Loop: A loop that never ends or called infinite loop.
printc",end="*)
2 Empty Statement: A statement that appears in the code but does nothing.
3. Body: The blocks of statement in a compound statenments that follows the header.
print( D"
Ans. =RESTART:
D/python class/code3.py
Output:
********** RE.TART: D:/pytho ciess11/Gutputi.py **muanuzsa
4. Nested Loop: A loop contains another loop inside its body. D > ***
A iPytnon_ Class1/outputl.pY ***=e*au
5. teration: set of instructions to be performed repeatedly.
Q6. What gets printed? You entered i7t
6. Entry-controlled loop: that control over entry in the loop in the form of test condition.
temp=int(input(""enter temperature")
if temp<32:
************* RE3TART: D:/PYthon ciass11/output!.py ****aon**u
* ***** atacte?
print(ice") nrer . r a t e c P T O n Ca35 cutputi.Fy w*m*=n*a*me
Solved Questions elif temp<212: ya entered an uyperca3e chiaracter
*aaauw=mvananazanz RESTART: D:/python class
i/Gutpatl.9Â¥****
entez a single characer:®
p C i a Charucter
print"water")
else:
Q1. Can you use one or more loop inside any another while, for or do.... while loop? print("steam")
Ans. Yes. Q10. Program to calculate the factorial of a number
Ans. enter temperature 37
Ans. nu1nt(input(enter a nnbe: "))
water
Q2 Write the name of loop which executes a sequence of statements multiple times and abbreviates the coue
manages the loop variable.
Tacc
>>>
acsnum:
"**
Ans. or-ioop. tact"
97 What would the follow ing code print if you input
the value 3?
a
printIactoti e Iact)
Q3. What is the output ofthe following?
i =0 n=intinput("enter an integer") Output:
while i < 3: if n<l: enter d unoEt
printii) print(invalid value")
else:
fori in range(1,n+1)
printi*i)
else: a c t o d l oL nnDer izU
Iactorial or numbeT 120
printi) Iactor1ai ot number 5040
260
mnuter Applicatio Conditions and Loops in Python
print("Input lengths of the triangie sides: ")
X = int (input ("x: "))
Y int (input("Y: "))
Z =
int (input("z: "))
Q11. Program to Reverse a Given Number Ans.
Ans. n=int (input("Enter number: "})
rev=0
.e(n>0)
dig=n$10
rev=rev*10+dig
n=n//10
print("ECquiiaterai triangle")
if x != y != z:
print("Reverse of the numioer: ", rev) print ("Scalene triarngie"))
Output: print("isosceles triangle")
Enter number: 123
Reverse of the number: 321
Output:
==== RESTART: D:/python class _11/pattern 3
Input engths of the triangle sides:
x:10
Y: 15
2: 19
Scalene triangle
Q12. Program to Print an Inverted Star Pattern.
n=int(input("Enter number of rows: "))
or i range (n,0,-1):
print (n-i) *
+ i * 'a'
Ans.
Output:
Enter number of rows: 4
==u====== RESTART: D:/python class 11/pattern
Input iengths of the triangle sides:
10
y: 10
2:
Equilatera! triangle
>>>
* * *
10
=== RESTART: D:/python class_1/pattern
Q13. Write a program to input 3 sides ofa triangle and
|Input 1engths of the triangle sides:
10
x
10
print whether and print whether it is an equilateral,
scalene or isosceles triangle.
Y:
z: 15
isosceles triangle

More Related Content

Similar to if else python.pdf

Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Notes on c++
Notes on c++Notes on c++
Notes on c++Selvam Edwin
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptxmalekaanjum1
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSKalaivaniD12
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 
GE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfGE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfAsst.prof M.Gokilavani
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Syed Farjad Zia Zaidi
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1Syed Farjad Zia Zaidi
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhtonPrakash Jayaraman
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)Niket Chandrawanshi
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentalsumar78600
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on SessionDharmesh Tank
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdfRohitSindhu10
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 

Similar to if else python.pdf (20)

Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 
C# p5
C# p5C# p5
C# p5
 
GE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfGE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdf
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
Introduction To Programming with Python-1
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
 
Python session3
Python session3Python session3
Python session3
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Programming Fundamentals
Programming FundamentalsProgramming Fundamentals
Programming Fundamentals
 
Basic of Python- Hands on Session
Basic of Python- Hands on SessionBasic of Python- Hands on Session
Basic of Python- Hands on Session
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
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
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 

Recently uploaded (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
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
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

if else python.pdf

  • 1. UNIT 4:SCRATCH OR PYTHON (THEORY AND PRACTICAL) 3. COMPOUND STATEMENT A compound statement represents a group of statements executed as a unit. The compound statements of python are written in a specific pattern as shown in example. Conditions and >>> testl=2 >>>test2=4 testi: Loops in Python >>> t test2: print (test1) Let's Recal Write advantages and disadvantages ofPython. What doyou mean by interactive mode programming and scripting mode of programming? STATEMENTS FLOW OF CONTROL Statementl SEQUENCE Sequence means the statements are being executed sequentially. This represents the default flow of statement. Statement2 Let's Learn At the end of this chapter, you should be able to: Comprehend and useconditionalstatements: if, if-else statements dComprehend and use loop structure: for, while Statement3 Fig. 1 Flow of Control Condition SELECTION The selection constructs means the execution of statements depending upon a condition. If condition evaluates to true. a course -of-action (a set of statements) is followed otherwise another course-of-action (a different set of statements) is followed. true false Let's Begin Statement(s) Python provides control statements that serves to state what has to be done by the program, when and under which condition(s). This chapter discusses conditional and looping statements in detail. Fig. 2 Flow of STATEMENTS false Selection Construct Decision tarementsarethe instructions given to the computer to perform any kind of action such as, data ITERATION movement, decision making, repetitive action etc. Statements form the smallest executable unit within a The iteration construct means repetition of a set-of-statements depending upon a condition till the time a condition is true (or false depending upon the loop). a set-of-statements are repeated again and again until the condition becomes false (or true). true Python program. Statements are always terminated by semicolon. Sequence TYPES OF STATEMENTS IN PYTHON 1. EMPTY STATEMENTS The simplest statement is the empty statement, which has nothing. In python empty statement is po IF STATEMENT Fig. 3 Flow of Iteration statement. The if statement is the conditional statement in python and it follows selection constructs (decision constructs). 2. SiMPLE STATEMENT The simplest form of if statements tests a condition and if the condition evaluates to true, it carries out some instructions and does nothing in case condition evaluates to false. It is comprised within a single logical line. For example: Syntax: name=input ("ert.I u! ame") # thls is a staement if test expression: - statement(s) Here, the program evaluates the test expression and will execute statement() only if the text expression is True. Conditions and Loops in Python
  • 2. Output: If the text expression is False. the statement(5) is not executed. Test false In Python, the body of the if statement is indicated by the indentation. Body tarts with an indentation and the first unintended line marks the end. Expression Python console Console 1/A 3 true Python interprets non-zero values as True. None and 0 are interpreted as False. Example 1: Print a given statement if the number is positive. Body of if [8]: In Python 3.7.0 Shell In [8]: runfile("D:/python class /statementsi.py', wdir='D: /python class ') x is less than y File Edit Shell Debug Options Window Help PYEhon 3.7.0 (v3.7.0:lbf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Inte 1)) on win32 Fig. 4 Flowchart for if Statement 2pcopyright ", "credits" or "license () " for more information. nun=3 >>> num>0: In [9]: print (num, "is a positive number. ") rint("*his is àways Tntea. ") Example 3: Program to test the divisibility of a number with another number. 3 is a positive number this is always printed. Spyder (Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help F-ELSE STATEMENT Editor D:python_ dass 11felse stat.py n else statement can be combined with an if statement. An else statement contains the block of code nat executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at nost only one else statement following if. Syntax: temp.Py ifelse stat.py 1 number1=int(input("enter first number: ")) 2 number2=int(input(""enter second number: ")) 3 remainder=number1%numberr2 4 if remainder==0: Test False Expression The syntax of the if..else statement is - print(number1, "is divisible by",number2) if expression: 6 else: True statement(s) print(number1, "is not divisible by", number2) else: Body of if Body ofelse statement() 10 Example 2: Find out which is greater Fig. 2 Flowchart for if.. Output: Spyder (Python 3.6) else statement File Edit Search Source Run Debug Consoles Projects Tools View Help IPython console Console 1/A 3 Python 3.6.5 JAnaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)] Type copyright", "credits" or "license" for more information. Editor D:python dass _11statements1.py { temp.py" statements.py statementsi.py - 1 Codin7: utf 2*** 3 Created on iue Sep 18 i4:22:39 2018 IPython 6.4.0 -- An enhanced Interactive Python. 5" In [1]: runfile( 'D:/python class /if else stat. .py', wdir='D: /python clàs ') 7 K=4 8y=5 9if(x*y): 10 print("x is less than y") ! else: enter first number :123 enter second number: 23 print("y is greater than x" 123 is not divisible by 23 13 Conditions and Loops in Python Computer Applica cations
  • 3. In a nested if construct. you can have an if..elif...else construct inside another if...elif...else construct. IF-ELIF STATEMENT ometimes a situation arises when there are several conditions. To handle such a situation. Python all adding any number of. elif clause after an if and before an else clause. allows Syntax: if expressionl: statement(s) elif expression3: elif expression4: statement{s) Syntax: statement(s) else: ifexpressionl: elif expression2 : elifexpression3: if expression2: else: else: statement1 statement_3 statement_5 statement_7 statements) statement() statement(s) statement_2 statement_4 statement_6 statement_8 Example 5: Print a value depending on the given condition. ***********°°* Spyder Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help . Example 4: Program to input the marks of 5 subjects and display the grade. Spyder (Python 3.6) Editor-D:Python dass lnested f.py Fie Edit Search Source Run Debug Consoles Projects Tools View Help temp-Py eise zat.-py untted1.py 3 grade.py nestedif.py 1 var 16 2 if (var 200) print ("Express ion value is less than 200") if (var = 150) print ("Which is 150") elif (var = 100): print (hich is 180") elif (var == S0): print( "uhich is 50") elif( var < 50): Editor - D:python dasS 11gradePY tep-Py f elsesat.PY untrtledi.py grade.py ?subi=int(input("Enter marks of the first subject: ")) sub2-int (input("Enter marks of ihe second subject: ")) 4 sub3=int(input("Enter marks of the third subject: ")) 5 sub4=int(input("Enter marks of the fourth subject: ")) subS=int(input("Enter marks of the fifth subject: ")) avg=(subl+sub2+sub3+sub4+sub5) /5 S if(avg>90): print("grade A") telif(avg>=88 and avg<98) 11 print "Expressi0n value is less than 50") 2 else: print (" Could not find true expression ")| 14 prirt grade ) 12 elif(avg>=76 and avg<80): 13 print grade ") 14 elif(avg>=60 and avg<70)): Output: 15 print("grade D") 16 else: Python console print("grade ) Console 1/A Output: Expression value is less than 200 Which is 180 Enter manrks of the first subject: 78 In (3]: Enter marks of the second subject: 98 Enter marks of the third subject: 95 LOOPING CONSTRUCTS Enter marks of the fourth subject: 89 Loopsare used to repeatedly execute the same code in a program. Python provides two types of looping Enter marks of the fifth subject: 85 constructs: Erade While statement (condition based loop) For statement (loop for a given number of times) NESTED IF STATEMENT InformationByte There may be a situation when you want to check for another condition after a condition resoivE true. In such a situation. you can use the nested if construct. The iteration statements allow a setof instructions to be performed repeatedly until a certain condition is full filled. The iteration statements are also called loops or looping statements. 252 Computer Application5 Onditions and LoopsinPy 253
  • 4. RANGE) FUNCTION What follows next is block of statement(). The statement(s) in BLOCK 1 keeps on executing till condition in while remains True: once the Before we start with loops, let us discuss range() function which Is used in for loop. range() fun.. generates a list and has a special sequence type. A sequence in python is a succession of values bound condition becomes False and if the else clause is written in while. then else will get executed. While loop together by a single name. may not execute even once, if the condition evaluates to false, initially. as the condition is tested before entering the loop. Example 6: Print numbers 1 to 10. Some python sequence types are: strings, list. tuples etc. The common use of range() function are: Spyder Python 3.6) range(<lower limit>, <upper limit>) #both limits should be integers File Edit Search Source Run Debug Consoles Projects Tools View Help The function in the form range (1.u) will provide a list having values starting from l,1+1,1+2. (u-1). range(0,8) Editor D:python dass_11while.Py list as[o.1.2.3,4.5.6.7] temp.py ifelse stat..py untitled1.py grade.py 3 nested f.py while.py 1 i-1 range(<lower limit>,<upper limit>,<step value>) #al values should be integers range(l.u.5) 2 while(i <=10): print (i), i it1 gers it will produce list having values as l, I+s, I+25..=u-1 range(0,10,2) it will produce list as [O,2.4.6.8] Output: range(5.0.-1) In [3]: runfile( 'D:/python_ class /vhile.py', wdir='D:/python_ <lass ") list[5.4.3,2.1] 2 3 range(<number>) it creates a list from O(zero) to <number>. For example: Range(5) 9 List as[o.1.2.3.4] 10 WHILE LoOP You can almost read the statement like English sentence. The first statement initialized the variable (controlling loop) and then while evaluates the condition. which is True so the block of statements It is a condition based loop. written next will be executed. Syntax: Last statement in the block ensures that, with every execution of loop. loop control variable moves while condition: # caondition is Boolean expression returning either True or False near to the termination point. If this does not happen then the loop will keep on executing infinitely. STATEMENT BLOCK 1 As soon as i becomes 11, condition in while will evaluate to False and this will terminate the locop. Telse: # optional part of while STATEMENT BLOCK 2] NESTED WHILE LOOP We can see that while looks like if statement. The staternent explains with keyword while foll by a Boolean condition followed by colon (:). Block of statement belonging to while can have another while statement, i.e., a while can contain another ed while. 254 Conditions and Loops in Python 255 r A P p l i c a t i o n
  • 5. Example 8: Program to find the sum of all numbers stored in a list. Example 7: Program with nested loop. Spyder (Python 3.6) Spyder (Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help File Edit Search Source Run Debug Consoles Projects Tools View HelpP Editor- D:python_dass11forloop1.pPY Cy ifelsestat..pyE untited1.py grade.py Editor D:python dass_11nested while.py nested if.py while.py nested while.p while.py nesi| 1# iist of.nunbers untitled1.py grade.py nestedif.py temp-py if else stat..py s 2 numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11] 1 i = 1 4 # Variable tO store the sun 2j 5 Sum = while 4: while j < 8: print(i, ",", i 4 i terate over the tist 8 for val in numbers: 9 sum = sum+val LO 11 12 print(" The sum is", um) Output: Output: Python console Python console Console 1/A Console2/A Console 1/A Python 3.6.5 |Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64) ] Type "copyright", "credits" or "license" for more information. Python 3.6.5 Anaconda, Inc.| (default, Mar 29 2018, 13:32:41) [MSC v.1900 64 bit (AMD64)1 Type "copyright", "credits" or "license" for more information . IPython 6.4.0 An enhanced Interactive Python. IPython 6.4.0 -- An enhanced Interactive Python. In [1]: In 1: runfile( "b:/python class/nested while.py', wdir='D:/python class') 1 In [1]: runfile("D:/python_ class / for loop1.py', wdir='D:/python_ class') The sum is 48 In [2]: FOR LOODP NESTED FoR LooÞP The for loop in Python is used to iterate over a sequence (list, tuple, string) or other objects. Iterating y contain arnotherloop in its body. This is called nested loop. But in nested loop. the inne e over a sequence is called traversal. loop must terminate before the outer loop. for loop can be nested within another for loop. Syntax: for each item Example 9: Nested for loop. in sequence for <val> in <sequence>: Spyder (Python 3.6) Body of for File Edit Search Source Run Debug Consoles Projects Tools View Help es Last i Here, val is the variable that takes the value of the item inside the reached sequence on each iteration. Editor D:Python class_11nested forloop-pY No Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation. statment3.py E3 1 for outer in range (6,10,4): for inner in range(1,outer,2): print (outer, inner) nested for loop-py 3 Bodyoffor Exit loop ig. 3 Flowchart of for Loo Conditions and Loops in Python 256 257 o m p u t e r Applications i o n s andL
  • 6. cONTINUE STATEMENT Output: Enter loop 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 n 1: runfile( D:/python lass /nested for loop.py', wdir='D:/python class") Test False expression of oop 6 3 with the next iteration. Syntax: True Continue JUMP STATEMENTSs BREAKANDCONTINUE Yes Python offers two jump statements to be used within loops tojump out of loop-iterations. These break and continue statements. s. These are Example 11: Program using continue Statement. Continue? Spyder(Python3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help Enter loop |No Exit loOP THE BREAK STATEMENT Test Remaining8 False Editor-D:python cass 11continuel.py body ofloop Ihe break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. expression of looP 19y gradepy nestedfpy3 while.py3 nested wnie.py PYunon.py or oop1.g Fig. 5 Flowchart of Continue 2 for val in "string": True 3 if val == "i": 4 continue If break statement is inside a nested loop (loop inside another loop). break will terminate the innermost loop. 5 print(val1) Yes Break? 7 print(The end") Syntax: No break Output: Exit loop Remaining bodyofloop Tn [4]: runfile( 'D: /python_ class /continue1 .Py', wdir='D: /python_ class ") Fig. 4 Flowchart of break Example 10: Theend Spyder (Python 3.6) File Edit Search Source Run Debug Consoles Projects Tools View Help Example 12: Program to illustrate the difference between break and continue statement. Spyder (Python3.6) File Edit Search Source Run Debug Consoles Projects Tools View HelpP Editor D:python dass_1iibreaki.py at-py untitied.Py gade.py nested f-py while.py nested while.py Pyon 1 for val in "string" : Editor-D:ythonclass_11statment3.py if val == "i": statment3.py break 1 #break condit ion print(val) 2print("the loop with break statement produces output as: 3 for i in range(1,10): if ik2==0: 6 print(The end") 4 break B else: print(i 8 #cont inue condtit ion Output: 9print("the loop with continue statement produces output as: ") 18 for i in range(1,10): In [2]: runfile( D:/python_ class (break1.py', wdir='D:/python_ class ') if ix2==0: 12 continue t L3 else: 4 print(i) The end Computer plication Conditions and Loops in Python 259 258
  • 7. Output: Ans. Ans. it will calculate square of numbers enter an integer3 lass/statment3.py', wdir='D:/python class ") In [7]: runfile( D. /python the loop with break statement produces output as the loop with continue statement produces output as Q4. Find the output offollowing code. =1 *2 1= 3 Q8. Write a program to check whether given numberis even or odd. sum= ANS. number=int (input ("enter any e")) for i in (x.y.2): number$2==0: if (isinstancei, int): print (number,"i an even nher")| Lets Summarise Sum =sum+i print (number, "1s an dd nunber ") print fsum) Output: Python supports selection orconditional statements. There are three types ofstatements in python, namely emply statements, simple statements. compound statements. The iteration constructs mean repetition of a set-of-Stalements depending upon a condition till the time a condition is true (or Ans. enter any nunber12 n even nunber Q5. What gets printed? false depending upon the loop), a set-of-statements are repeated again and again. Q9. Program to print whetlher a given character is an if x>3: uppercase or a lowercase character or a digit or any other character. A Compound statement represents a group of statements executed as a unit. if x>4: ------~----- -----*- printA",end=" ") AnS. character iiput"entei d ligL cia ") Character>*' 11d charaCter<='2': else: Glossary haTActe .tLacter") charact printB".end="*") , . prnt("yo 7t charactetx"i ' ai character<'': P a t e i r u ilg if(x!=0): . Endless Loop: A loop that never ends or called infinite loop. printc",end="*) 2 Empty Statement: A statement that appears in the code but does nothing. 3. Body: The blocks of statement in a compound statenments that follows the header. print( D" Ans. =RESTART: D/python class/code3.py Output: ********** RE.TART: D:/pytho ciess11/Gutputi.py **muanuzsa 4. Nested Loop: A loop contains another loop inside its body. D > *** A iPytnon_ Class1/outputl.pY ***=e*au 5. teration: set of instructions to be performed repeatedly. Q6. What gets printed? You entered i7t 6. Entry-controlled loop: that control over entry in the loop in the form of test condition. temp=int(input(""enter temperature") if temp<32: ************* RE3TART: D:/PYthon ciass11/output!.py ****aon**u * ***** atacte? print(ice") nrer . r a t e c P T O n Ca35 cutputi.Fy w*m*=n*a*me Solved Questions elif temp<212: ya entered an uyperca3e chiaracter *aaauw=mvananazanz RESTART: D:/python class i/Gutpatl.9Â¥**** entez a single characer:® p C i a Charucter print"water") else: Q1. Can you use one or more loop inside any another while, for or do.... while loop? print("steam") Ans. Yes. Q10. Program to calculate the factorial of a number Ans. enter temperature 37 Ans. nu1nt(input(enter a nnbe: ")) water Q2 Write the name of loop which executes a sequence of statements multiple times and abbreviates the coue manages the loop variable. Tacc >>> acsnum: "** Ans. or-ioop. tact" 97 What would the follow ing code print if you input the value 3? a printIactoti e Iact) Q3. What is the output ofthe following? i =0 n=intinput("enter an integer") Output: while i < 3: if n<l: enter d unoEt printii) print(invalid value") else: fori in range(1,n+1) printi*i) else: a c t o d l oL nnDer izU Iactorial or numbeT 120 printi) Iactor1ai ot number 5040 260 mnuter Applicatio Conditions and Loops in Python
  • 8. print("Input lengths of the triangie sides: ") X = int (input ("x: ")) Y int (input("Y: ")) Z = int (input("z: ")) Q11. Program to Reverse a Given Number Ans. Ans. n=int (input("Enter number: "}) rev=0 .e(n>0) dig=n$10 rev=rev*10+dig n=n//10 print("ECquiiaterai triangle") if x != y != z: print("Reverse of the numioer: ", rev) print ("Scalene triarngie")) Output: print("isosceles triangle") Enter number: 123 Reverse of the number: 321 Output: ==== RESTART: D:/python class _11/pattern 3 Input engths of the triangle sides: x:10 Y: 15 2: 19 Scalene triangle Q12. Program to Print an Inverted Star Pattern. n=int(input("Enter number of rows: ")) or i range (n,0,-1): print (n-i) * + i * 'a' Ans. Output: Enter number of rows: 4 ==u====== RESTART: D:/python class 11/pattern Input iengths of the triangle sides: 10 y: 10 2: Equilatera! triangle >>> * * * 10 === RESTART: D:/python class_1/pattern Q13. Write a program to input 3 sides ofa triangle and |Input 1engths of the triangle sides: 10 x 10 print whether and print whether it is an equilateral, scalene or isosceles triangle. Y: z: 15 isosceles triangle