You are on page 1of 55

INT102

Conditionals
and
Iterations
Operators
Types of Operator

• Arithmetic Operators
• Unary Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Assignment Operators
• Membership Operators
• Logical Operators
• Identity Operators
Arithmetic Operators

• + Addition
• - Subtraction
• * Multiplication
• / Division
• %Modulus (Remainder)
• // Floor Division( removes digit after decimal point)
• ** Exponent (Raise to)
The modulus operator

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


and yields the remainder when the first operand is divided by the
second.
• In Python, the modulus operator is a percent sign (%).
Example
• 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.
Uses

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


then x is divisible by y.
• you can extract the right-most digit or digits from a number.
• For example,
x % 10 yields the right-most digit of x (in base 10). Similarly x % 100
yields the last two digits.
Boolean expressions

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


• One way to write a Boolean expression is to use the operator ==,
which compares two values and produces a Boolean value:
>>> 5 == 5
True
>>> 5 == 6
False
• True and False are special values that are built into Python.
Boolean expressions examples
• import random
• n1=random.randint(1,9)
• n2=random.randint(1,9)
• ans=eval(input("What is "+str(n1)+" + "+str(n2)+" "))
• print("Your ans is ",n1+n2==ans)
• Print(int(true))
Displays 1
• Print(int(false))
Displays 0
• Print(bool(0))
Displays false
• Print(bool(4))
Displays true
Comparison Operators

• 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=<y # x is greater than or equal to y
• x <= y # x is less than or equal to y
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:


❖ and,
❖ or
❖ not
• 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
• not(x > y) is true if (x > y) is false, that is, if x is less than or equal to y.
Logical operators example

• Print(bool(5>0 and 4>0))


• Displays true
• Print(bool(5>0 and 4<0))
• Displays false
• Print(bool(5>0 or 4>0))
• Displays true
• Print(bool(5>0 or 4<0))
• Displays true
Logical operators example

• X=true
• Y=false
• Print(“x and y is”,x and y) #output: false
• Print(“x or y is”,x or y) #output: true
• Print(“not x is”,not x) #output: false


Identity operators

• Identity operators compare the memory locations of two objects.


There are two Identity operators as explained below
Bitwise Operators( cannot be applied to float or double variables)

~10101011 = 01010100
Membership Operators
Continue…

• Any nonzero number is interpreted as “true."


>>> x = 5
>>> x and 1
1
>>> y = 0
>>> y and 1
0
• Q1. WAP to read the marks of 5 subjects through keyboard. Find out
the aggregate and percentage of marks obtained by the student.
Assume maximum marks that can be obtained by a student in each
subject as 100.
• Q2. WAP to read a four digit number through keyboard and calculate
the sum of its digits.
• Q3. Read a distance in meters and a time in seconds through the
keyboard. WAP to calculate the speed of a car in meter/second.
Keyboard Input
• input(): built in function to get data from keyboard.
• Takes data in the form of string.
• Eg:
>>> input1 = input ()
What are you waiting for?
>>> print input1
What are you waiting for?
• Before calling input, it is a good idea to print a message telling the user
what to input. This message is called a prompt.
• A prompt can be supplied as an argument to input.
• Eg:
>>> name = input ("What...is your name? ")
What...is your name? Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
• If we expect the response to be an integer, then type conversion needs
to be done.
• Eg:
prompt = "What is the airspeed velocity of an unladen swallow?"
speed =int(input(prompt))
Conditional Execution

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


change the behaviour of the program accordingly.
• Different conditional statements in python are:
– IF
– IF ---Else (Alternative Execution)
– IF--- ELIF---- ELSE (Chained Conditionals)
– Nested Conditionals
If Condition
• If x > 0:
print "x is positive“
• The Boolean expression after the if statement is called the condition. If
it is true, then the indented statement gets executed. If not, nothing
happens.
• Structure of If
– HEADER:
FIRST STATEMENT
...
LAST STATEMENT
If Condition
• There is no limit on the number of statements that can appear in the
body of an if statement, but there has to be at least one.
• Occasionally, it is useful to have a body with no statements (usually as a
place keeper for code you haven't written yet). In that case, you can use
the pass statement, which does nothing.
If Condition example

• If a > 0:
print (“a is positive”)
Alternative Execution
• A second form of the if statement is alternative execution, in which
there are two possibilities and the condition determines which one gets
executed.
• Eg:
if x%2 == 0:
print (x, "is even“)
else:
print (x, "is odd“)
• The alternatives are called branches.
If else Condition example

• r=eval(input("Enter input "))


• if(r<0):
• print("Wrong input")
• else:
• print("true value")

Continue….

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


alternatives will be executed. The alternatives are called branches,
because they are branches in the flow of execution.
Chained Conditionals
• Sometimes there are more than two possibilities and we need more
than two branches.
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
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
Nested conditionals
• One conditional can also be nested within another.
if x == y:
print x, "and", y, "are equal"
else:
if x < y:
print x, "is less than", y
else:
print x, "is greater than", y
if 0 < x and x < 10:
print "x is a positive single digit.“

• Python provides an alternative syntax that is similar to mathematical


notation:
if 0 < x < 10:
print "x is a positive single digit."
Shortcuts for Conditions
• Numeric value 0 is treated as False
• Empty sequence "", [] is treated as False
• Everything else is True
if m%n:
(m,n) = (n,m%n)
else:
gcd = n
Wrapping of IF-ELSE into one function.
• Function is a block of code that performs a specific function.
• In python, function is defined by keyword “def”.
• For example:
def printParity(x):
if x%2 == 0:
print x, "is even"
else:
print x, "is odd“
• 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)
17 is odd
>>> y = 17
>>> printParity(y+1)
18 is even
Example
Calling of function depending upon input enter by user:
Example:
if choice == 'A':
functionA()
elif choice == 'B':
functionB()
elif choice == 'C':
functionC()
else:
print "Invalid choice."
Avoid Nested If

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


conditional:
if 0 < x:
if x < 10:
print "x is a positive single digit.“
Better way:
if 0 < x and x < 10:
print "x is a positive single digit."
Q1. WAP to find even and odd numbers
Q2. WAP to find whether number is a prime number or not.
Q3. Write a Python program to check whether an alphabet is a
vowel or consonant.
Q4. Write a Python program to check a triangle is equilateral,
isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three
sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal
sides.
The Return Statement

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


function before you reach the end.
• Example
def evenodd(x):
if x%2:
return(True)
else:
return(False)
ITERATION
Doing the Same Thing Many Times

• It’s possible to do something repeatedly by just writing it all out


• Print ‘hello’ 5 times
>>> print('Hello!')
Hello
>>> print('Hello!')
Count n Hello
times >>> print('Hello!')
Hello
>>> print('Hello!')
Hello
Statements >>> print('Hello!')
Hello
Iteration and Loops
• A loop repeats a sequence of statements
• A definite loop repeats a sequence of statements a predictable number
of times

>>> for x in range(5): print('Hello!')


...
Hello
Count n Hello
times Hello
Hello
Hello
Statements
The for Loop
• Python’s for loop can be used to iterate a definite number of times
for <variable> in range(<number of times>): <statement>
• Use this syntax when you have only one statement to repeat
for <variable> in range(<number of times>):
<statement-1>
<statement-2>

<statement-n> >>> for x in range(3):
... print('Hello!')
... print('goodbye')
•Use indentation to format two or ...
Hello!
more statements below the loop goodbye
Hello!
header goodbye
Hello!
goodbye
Using the Loop Variable
• The loop variable picks up the next value in a sequence on each pass
through the loop
• The expression range(n) generates a sequence of ints from 0
through n - 1
loop variable

>>> for x in range(5): print(x)


...
0
1
2
3
4
>>> list(range(5)) # Show as a list
[0, 1, 2, 3, 4]
Counting from 1 through n

• The expression range(low, high) generates a sequence of ints from low


through high - 1

>>> for x in range(1, 6): print(x)


...
1
2
3
4
5
Counting from n through 1

• The expression range(high, low, step) generates a sequence of ints


from high through low+1.

>>> for x in range(6, 1, -1): print(x)


...
6
5
4
3
2
Skipping Steps in a Sequence

• The expression range(low, high, step) generates a sequence of ints


starting with low and counting by step until high - 1 is reached or
exceeded
>>> for x in range(1, 6, 2): print(x)
...
1
3
5
>>> list(range(1, 6, 2)) # Show as a list
[1, 3, 5]
Using a Loop in a Real Problem
• An investor deposits $10,000 with the Get-Rich-Quick agency and
receives a statement predicting the earnings on an annual percentage
rate (APR) of 6% for a period of 5 years. Write a program that prints the
beginning principal and the interest earned for each year of the period.
The program also prints the total amount earned and the final principal.
• Pseudocode: principal = 10000
rate = .06
term = 5
totalinterest = 0
for each year in term
print principal
interest = principal * rate
print interest
principal = principal + interest
totalinterest = totalinterest + interest
print totalinterest
print principal
While Loop
A for loop is used when a program knows it needs to repeat a block of
code for a certain number of times.
A while loop is used when a program needs to loop until a particular
condition occurs.
Flow of Execution for WHILE Statement
Looping Until User Wants To Quit
Range Function
• Range returns an immutable sequence objects of integers between
the given start integer to the stop integer.
• range() constructor has two forms of definition:
– range(stop)
– range(start, stop, step)
• start - integer starting from which the sequence of integers is to be returned
• integer before which the sequence of integers is to be returned.
The range of integers end at stop - 1.
– step (Optional) - integer value which determines the increment between each integer in
the sequence
• Range(5) ----- [0,1,2,3,4]
• Range(1,5) ----[1,2,3,4]
• Range(1,10,2)—[1,3,5,7,9]
• Range(5,0,-1)----[5,4,3,2,1]
• Range(5,0,-2)----[5,3,1]
• Range(-4,4)---- [-4,-3,-2,-1,0,1,2,3]
• Range(1,1)--- empty
• Range(0,1)--- 0
• Range(0)--- empty
Exercise
1. Write a password guessing program to keep track of how many
times the user has entered the password wrong. If it is more than 3
times, print "You have been denied access." and terminate the
program. If the password is correct, print "You have successfully
logged in." and terminate the program.
2. Write a program that asks for two numbers. If the sum of the
numbers is greater than 100, print "That is a big number" and
terminate the program.
3. Write a Python program that accepts a word from the user and
reverse it.
4. Write a python program to find those numbers which are divisible
by 7 and multiples of 5, between 1500 and 2700.
5. Write a Python program to get the Fibonacci series between 0 to 50.
6. Write a Python program which iterates the integers from 1 to 50. For multiples of
three print "Fizz" instead of the number and for the multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz“
7. Write a Python program to print alphabet pattern 'A'.
8. Write a Python program to print alphabet pattern 'D‘.
9. Write a Python program to check whether an alphabet is a vowel or consonant.
10. Write a Python program to check a triangle is equilateral, isosceles or scalene.
Note :An equilateral triangle is a triangle in which all three sides are equal.
A scalene triangle is a triangle that has three unequal sides.
An isosceles triangle is a triangle with (at least) two equal sides.

You might also like