Professional Documents
Culture Documents
Conditionals
by
Prathiksha Pai
Boolean expressions
• A Boolean expression is an expression that is either true or false. The following
examples use the operator ==, which compares two operands and produces True if
they are equal and False otherwise:
>>> 5 == 5
True
>>> 5 == 6
False
• True and False are special values that belong to the type bool; they are not strings:
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
• The == operator is one of the relational operators; the others are:
• x != y # x is not equal to y
• x > y # x is greater than y
• x < y # x is less than y
• x >= y # x is greater than or equal to y
• x <= y # x is less than or equal to y
• Modulus operator
• The modulus operator works on integers and yields the remainder when the first
operand is divided by the second. In Python, the modulus operator is a percent sign
(%). The syntax is the same as for other operators:
>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>> print remainder
1
• So 7 divided by 3 is 2 with 1 left over.
There are three logical operators: and, or, and not.
The semantics (meaning) of these operators is similar to their meaning
in English.
For example, x > 0 and x < 10 is true only if x is greater than 0 and less
than 10.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is,
if the number is divisible by 2 or 3.
Conditional statement (if)
• Conditional statements give us the ability to check conditions and
change the behaviour of the program accordingly.
The syntax for if statement:
if <test_expression>:
<body>
• Eg:
num = 3
if num > 0:
print(num, "is a positive number.")
num = -1
if num > 0:
print(num, "is a positive number.")
if <test_expression>:
<body_1>
else:
<body_2>
• Eg:
#Program checks if the number is positive or negative
num = 3
if num > 0:
print("Positive number")
else:
print("Negative number")
Chained conditionals (if-elif-else)
• Sometimes there are more than two possibilities and we need more
than two branches.
• The syntax looks like this:
if <test_expression_1>:
<body 1>
elif <test_expression_2>:
<body 2>
elif <test_expression_3>:
<body 3>
….
else:
<body N>
#Try these two variations as well:
#num = 0
#num = -4.5
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Ex 2:
if choice == 'a’:
draw_a()
elif choice == 'b’:
draw_b()
elif choice == 'c’:
draw_c()
Iteration
The while statement
• The keyword while followed by a test expression (which can be any
valid expression), and a colon.
• Following the header is an indented body. The test expression is
evaluated.
• If it evaluates to True, then the body of the loop is executed. After
executing the body, the test expression is evaluated again.
• While test expression evaluates to True, the body of the loop is
executed.
• When the test expression evaluates to False, the loop is terminated and
execution continues with the statement following the body.
• Syntax: while <test_expression>:
<body>
Print n natural numbers
i=1
while(i<=5):
print(i)
i=i+1
Output
5
The for Statement
• Python’s for statement iterates over the items of any sequence (a list or
a string), in the order that they appear in the sequence.
Syntax:
for val in sequence:
Body of for
# Program to find the sum of all numbers stored in a list
#List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0 #variable to store the sum
for val in numbers: #iterate over the list
sum = sum+val
print("The sum is", sum)
Output
1234
Python break and continue
Break:
• The break statement terminates the loop containing it. Control of the
program flows to the statement immediately after the body of the loop.
• The working of break statement in for loop and while loop is shown
below.
Eg:
for val in “string”:
if val == “i”:
break
print(val)
Print(“the end”)
Output: s
t
r
the end
Continue:
Print(“the end”)
Output: s
t
r
n
g
the end
Pass:
• In Python programming, the pass statement is a null statement.
The difference between a comment and a pass statement in
Python is that while the interpreter ignores a comment entirely,
pass is not ignored.
• However, nothing happens when the pass is executed. It results
in no operation.
• Syntax:
pass
Suppose we have a loop or a function that is not implemented
yet, but we want to implement it in the future. They cannot have
an empty body. The interpreter would give an error. So, we use
the pass statement to construct a body that does nothing.
Example 1:
Sequence={‘p’, ’a’, ’s’, ’s’}
for val in sequence:
pass
Example 2:
while True:
pass
Example 3:
def function():
pass
FRUITFUL FUNCTIONS
Return values
• The built-in functions we have used, such as abs, pow, and max, have
produced results.
• Calling each of these functions generates a value,
which we usually assign to a variable or use as part of an expression.
biggest = max(3, 7, 2, 5)
x = abs(3 - 11) + 10
But so far, none of the functions we have written has returned a value.
In this chapter, we are going to write functions that return values, which
we will call fruitful functions
def area(radius):
temp = 3.14159 * radius**2
return temp
• We have seen the return statement before, but in a fruitful function the
return statement includes a return value.
• This statement means: Return immediately from this function and use
the following expression as a return value.
• The expression provided can be arbitrarily complicated, so
we could have written this function more concisely:
def area(radius):
return 3.14159 * radius**2
• We have already seen the built-in abs, now we see how to write our
own:
def absolute_value(x):
if x < 0:
return -x
else:
return x
• Since these return statements are in an alternative conditional, only
one will be executed. As soon as one is executed, the function
terminates without executing any subsequent statements.
• Another way to write the above function is to leave out the else and
just follow the if condition by the second return statement.
def absolute_value(x):
if x < 0:
return -x
return x
• Think about this version and convince yourself it works the same as
the first one.
• Code that appears after a return statement, or any other place the flow
of execution can never reach, is called dead code.
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where
the variable is recognized. Parameters and variables
defined inside a function is not visible from outside.
Hence, they have a local scope.
Variable max is defined outside func1 and func2 and therefore “global” to each.
Function Composition
• As you should expect by now, you can call one function from
within another. This ability is called composition.
• As an example, we’ll write a function that takes two points,
The center of the circle and a point on the perimeter, and
computes the area of the circle.
• Assume that the center point is stored in the variables xc and
yc, and the perimeter point is in xp and yp. The first step is to
find the radius of the circle, which is the distance between the
two points. Fortunately, we’ve just written a function,
distance, that does just that, so now all we have to do is use it:
The reason for the error is that strings are immutable, which means
you can’t change an existing string. The best you can do is create a new
string that is a variation on the original:
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!
>>>fruit = ‘apple'
>>>len(fruit)
5
• To get the last character, you have to subtract 1 from length:
Output:
num=2
exp=3
result is 8
4. Sum of array of numbers
arr=[1,3,3,4,5]
sum=0
for i in range(0,len(arr)):
sum=sum+arr[i]:
print(“sum of all the elements of an array:”, sum)