Conditionals and Iteration | PDF | Boolean Data Type | Computer Programming
0% found this document useful (0 votes)
13 views

Conditionals and Iteration

This document discusses conditional statements in Python. It explains if statements and else clauses for alternative execution based on a Boolean condition. It provides examples of using comparison, logical, and identity operators to write conditions. It also introduces continue, continue, and else clauses that allow for chained conditional execution with multiple branches. The key purpose of conditional statements is to check conditions and change program behavior accordingly.

Uploaded by

Jatin Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Conditionals and Iteration

This document discusses conditional statements in Python. It explains if statements and else clauses for alternative execution based on a Boolean condition. It provides examples of using comparison, logical, and identity operators to write conditions. It also introduces continue, continue, and else clauses that allow for chained conditional execution with multiple branches. The key purpose of conditional statements is to check conditions and change program behavior accordingly.

Uploaded by

Jatin Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

un

iv
er
si
ty
st
ud
y.
in
Conditionals
The modulus operator

• The modulus operator works on integers (and integer expressions)

in
and yields the remainder when the first operand is divided by the

y.
ud
second.

st
• In Python, the modulus operator is a percent sign (%).

ty
si
er
iv
un
Example
• The syntax is the same as for other operators:

in
>>> quotient = 7 / 3

y.
ud
>>> print quotient

st
2

ty
si
>>> remainder = 7 % 3

er
iv
>>> print remainder un
1
• So 7 divided by 3 is 2 with 1 left over.
Uses

• Check whether one number is divisible by another if x % y is zero,

in
then x is divisible by y.

y.
ud
• you can extract the right-most digit or digits from a number.

st
• For example,

ty
si
er
x % 10 yields the right-most digit of x (in base 10). Similarly x % 100

iv
yields the last two digits.
un
Boolean expressions

• A Boolean expression is an expression that is either true or false.

in
• One way to write a Boolean expression is to use the operator ==,

y.
ud
which compares two values and produces a Boolean value:

st
ty
>>> 5 == 5

si
er
True
>>> 5 == 6
iv
un
False
• True and False are special values that are built into Python.
Comparison Operators

• x != y # x is not equal to y

in
• x>y

y.
# x is greater than y

ud
• x<y # x is less than y

st
ty
• x >= y # x is greater than or equal to y

si
er
• x <= y # x is less than or equal to y
iv
un
NOTE: “= is an assignment operator and == is a comparison operator”.
Also, there is no such thing as =< or =>.
Logical operators

• There are three logical operators:

in
❖ and,

y.
ud
❖ or

st
❖ not

ty
si
• For example, x > 0 and x < 10 is true only if x is greater than 0 and less

er
than 10.

iv
un
• n%2 == 0 or n%3 == 0
• not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.
Identity operators

• Identity operators compare the memory locations of two objects.

in
There are two Identity operators as explained below

y.
ud
st
ty
si
er
iv
un
Example

..\..\..\..\Python27\is.py

in
y.
ud
st
ty
si
er
iv
un
un
iv
er
si
ty
st
ud
y.
in
Bitwise Operators
Membership Operators

in
y.
ud
st
ty
si
er
iv
un
• a = 10

in
• b = 20

y.
ud
• list = [1, 2, 3, 4, 5 ];

st
ty
• if ( a in list ):

si
er
• print "Line 1 - a is available in the given list"
iv
un
• else:
• print "Line 1 - a is not available in the given list"
Continue…

• Any nonzero number is interpreted as “true."

in
y.
>>> x = 5

ud
>>> x and 1

st
ty
1

si
er
>>> y = 0
iv
un
>>> y and 1
0
Conditional Execution

• To write useful programs we need the ability to check conditions and

in
change the behaviour of the program accordingly.

y.
ud
• Conditional statements give us this ability. The simplest form is the if

st
statement:

ty
si
if x > 0:

er
iv
print "x is positive“ un
The Boolean expression after the if statement is called the condition.
Basic Structure of If Statement

• Like other compound statements, the if statement is made up of a

in
header and a block of statements:

y.
ud
HEADER:

st
ty
FIRST STATEMENT

si
BLOCK

er
...

iv
LAST STATEMENT un
Alternative execution

• A second form of the if statement is alternative execution, in which

in
there are two possibilities and the condition determines which one

y.
ud
gets executed.

st
• The syntax looks like this:

ty
si
>>if x%2 == 0:

er
iv
print x, "is even“ un
>>else:
print x, "is odd"
Continue….

• Since the condition must be true or false, exactly one of the

in
alternatives will be executed. The alternatives are called branches,

y.
ud
because they are branches in the flow of execution.

st
ty
si
er
iv
un
Wrapping of IF-ELSE into one function.

def printParity(x):

in
y.
if x%2 == 0:

ud
print x, "is even"

st
ty
else:

si
er
print x, "is odd“
iv
un
• For any value of x, printParity displays an appropriate message. When
you call it, you can provide any integer expression as an argument.
Example

>>> printParity(17)

in
y.
17 is odd

ud
>>> y = 17

st
ty
>>> printParity(y+1)

si
er
18 is even
iv
un
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.

in
y.
if x < y:

ud
print x, "is less than", y

st
ty
elif x > y:

si
er
print x, "is greater than", y
iv
un
else:
print x, "and", y, "are equal“
NOTE: There is no limit of the number of elif statements, but the last
branch has to be an else statement
Example
if choice == 'A':

in
functionA()

y.
ud
elif choice == 'B':

st
functionB()

ty
si
elif choice == 'C':

er
iv
functionC() un
else:
print "Invalid choice."
• Assignment :

in
y.
“Calculator in Python”

ud
st
..\..\..\..\Python27\cal.py

ty
si
er
iv
un
Nested conditionals
• One conditional can also be nested within another.

in
if x == y:

y.
ud
print x, "and", y, "are equal"

st
else:

ty
si
if x < y:

er
iv
print x, "is less than", y
un
else:
print x, "is greater than", y
Avoid Nested If

• For example, We can rewrite the following code using a single

in
conditional:

y.
ud
if 0 < x:

st
ty
if x < 10:

si
er
print "x is a positive single digit.“
Better way:
iv
un
if 0 < x and x < 10:
print "x is a positive single digit."
The Return Statement

• The return statement allows you to terminate the execution of a

in
function before you reach the end.

y.
ud
st
ty
si
er
iv
un
un
iv
er
si
ty
st
ud
y.
in
ITERATION
Multiple assignment

in
y.
ud
st
ty
si
er
iv
un
The while statement

• Computers are often used to automate repetitive tasks.

in
• Repeating identical or similar tasks without making errors is

y.
ud
something that computers do well and people do poorly.

st
ty
si
er
iv
un
un
iv
er
si
ty
st
Example

ud
y.
in
Flow of Execution for WHILE Statement

in
y.
ud
st
ty
si
er
iv
un
Program 1

• count = 0

in
• while (count < 9):

y.
ud
• print 'The count is:', count

st
ty
• count = count + 1

si
er
• print "Good bye!"
iv
un
• count = 0 • count = 0

in
• while (count < 9): • while count < 5:

y.
ud
• print 'The count is:', count • print count, " is less than 5"

st
ty
• count = count + 1 • count = count + 1

si
er
• print "Good bye!" • else:

iv
un • print count, " is not less than 5"
For loop structure

• for letter in 'Python':

in
• # First Example

y.
ud
• print 'Current Letter :', letter

st
ty
• # second example

si
er
• fruits = ['banana', 'apple',

iv
un 'mango']
• for fruit in fruits:
• print 'Current fruit :', fruit
• print "Good bye!"
• fruits = ['banana', 'apple', • # display prime no. from 1-20

in
'mango']

y.
ud
• for index in range(len(fruits)):

st
print 'Current fruit :', fruits[index]

ty
print "Good bye!"

si
er
iv
un
• for num in range(10,20):

in
• for i in range(2,num):

y.
ud
• if num%i == 0:

st
ty
• j=num/i

si
er
• print '%d equals %d * %d' % (num,i,j)
iv
un
• break
• else:
• print num, 'is a prime number'
Nested loops

• i=2

in
• while(i < 100):

y.
ud
• j=2

st
ty
• while(j <= (i/j)):

si
er
• if not(i%j): break
iv
un
• j=j+1
• if (j > i/j) : print i, " is prime"
• i=i+1
print "Good bye!"
Encapsulation

• Encapsulation is the process of wrapping a piece of code in a

in
function, allowing you to take advantage of all the things functions

y.
ud
are good for.

st
• Example:

ty
si
er
iv
un
Generalization

• Generalization means taking something specific and making it more

in
general, such as printing the multiples of 2 as printing the multiples of

y.
ud
any integer.

st
ty
si
er
iv
un

Specific code Generalization


un
iv
er
si
ty
st
ud
y.
in
Output of Example
un
iv
er
si
ty
st
ud
y.
in
Another Example
un
iv
er
si
ty
st
OUTPUT

ud
y.
in
• N=input(‘enter a number’)

in
• i=2

y.
ud
• S=0

st
ty
• While(i<n/2)

si
er
• If(n%i==0)
iv
un
• Print “composite”
• S=1
• Break
• i=i+1

You might also like