0% found this document useful (0 votes)
83 views29 pages

Lecture 3 Branching and Iterations

Uploaded by

thanh vu duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views29 pages

Lecture 3 Branching and Iterations

Uploaded by

thanh vu duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Lecture 3:

Branching and Iterations in Python

Dr. Naveen Saini

Assistant Professor,
Department of Technology Studies,
Endicott College of International Studies,
Woosong University,
Daejeon, South Korea
Dr. Naveen Saini | ECIS 1
[email protected]
Any question about the previous
lectures????

Dr. Naveen Saini | ECIS 2


Working with Google Colab
Google Colab or “the Colaboratory” is a free cloud service hosted by Google to
encourage Machine Learning and Artificial Intelligence research, where often the
barrier to learning and success is the requirement of tremendous computational
power.

Create a Colab Notebook


1.Open Google Colab.
2.Click on ‘New Notebook’ and select Python 2 notebook or
Python 3 notebook.

OR

1.Open Google Drive.


2.Create a new folder for the project.
3.Click on ‘New’ > ‘More’ > ‘Colaboratory’.
4.Type of the name of your opened file and start
programming.
An Example program using Google Colab

Program to add numbers from 1 to n, where n is input by


user.
If right clear, If right blocked, If right and If right , front,
go right go forward front blocked, left blocked,
go left go back

6.0001 LECTURE 2 10
CONTROL FLOW - BRANCHING
if <condition>: if <condition>:
<expression> <expression>
<expression> <expression>
... ...
elif <condition>:
if <condition>: <expression>
<expression> <expression>
<expression> ...
... else:
else: <expression>
<expression> <expression>
<expression> ...
...

 <condition> has a value True or False


 evaluate expressions in that block if <condition> is True

6.0001 LECTURE 2 11
INDENTATION
 matters in Python
 how you denote blocks of code
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")

6.0001 LECTURE 2 12
= vs ==
x = float(input("Enter a number for x: "))
y = float(input("Enter a number for y: "))
if x == y:
print("x and y are equal")
if y != 0:
print("therefore, x / y is", x/y)
elif x < y:
print("x is smaller")
else:
print("y is smaller")
print("thanks!")

6.0001 LECTURE 2 13
 Legend of Zelda –
Lost Woods
 keep going right,
takes you back to this
same screen, stuck in
a loop
Image Courtesy Nintendo, All Rights Reserved. This content is excluded from our Creative
Commons license. For more information, see http://ocw.mit.edu/help/faq-fair-use/.
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
if <exit right>:
<set background to woods_background>
and so on and on and on...
else:
<set background to exit_background>
else:
<set background to exit_background>
else:
<set background to exit_background>

6.0001 LECTURE 2 14
 Legend of Zelda –
Lost Woods
 keep going right,
takes you back to this
same screen, stuck in
a loop
Word Cloud copyright unknown, All Right Reserved. This content is excluded from our Creative
Commons license. For more information, see http://ocw.mit.edu/help/faq-fair-use/.

while <exit right>:


<set background to woods_background>
<set background to exit_background>

6.0001 LECTURE 2 15
CONTROL FLOW:
while LOOPS
while <condition>:
<expression>
<expression>
...
 <condition> evaluates to a Boolean
 if <condition> is True, do all the steps inside the
while code block
 check <condition> again
 repeat until <condition> is False

6.0001 LECTURE 2 16
while LOOP EXAMPLE
You are in the Lost Forest.
************
************

************
************
Go left or right?

PROGRAM:

n = input("You're in the Lost Forest. Go left or right? ")


while n == "right":
n = input("You're in the Lost Forest. Go left or right? ")
print("You got out of the Lost Forest!")

6.0001 LECTURE 2 17
CONTROL FLOW:
while and for LOOPS
 iterate through numbers in a sequence

# more complicated with while loop


n = 0
while n < 5:
print(n)
n = n+1

# shortcut with for loop


for n in range(5):
print(n)

6.0001 LECTURE 2 18
CONTROL FLOW: for LOOPS
for <variable> in range(<some_num>):
<expression>
<expression>
...

 each time through the loop, <variable> takes a value


 first time, <variable> starts at the smallest value
 next time, <variable> gets the prev value + 1
 etc.
6.0001 LECTURE 2 19
range(start,stop,step)
 default values are start = 0 and step = 1 and optional
 loop until value is stop - 1

mysum = 0
for i in range(7, 10):
mysum += i
print(mysum)

mysum = 0
for i in range(5, 11, 2):
mysum += i
print(mysum)

6.0001 LECTURE 2 20
break STATEMENT
 immediately exits whatever loop it is in
 skips remaining expressions in code block
 exits only innermost loop!

while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>
6.0001 LECTURE 2 21
break STATEMENT
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
mysum += 1
print(mysum)

 what happens in this program?

6.0001 LECTURE 2 22
for VS while LOOPS
for loops while loops
 know number of  unbounded number of
iterations iterations
 can end early via  can end early via break
break  can use a counter but
must initialize before loop
 uses a counter and increment it inside loop
 can rewrite a for loop  may not be able to
using a while loop rewrite a while loop using
a for loop

6.0001 LECTURE 2 23
Practical Session

My Google Colab Link


https://colab.research.google.com/drive/18ZNM_Neid
gybLvaONy753jhcxwtHzee1?usp=sharing

Dr. Naveen Saini | ECIS 1


Multiple Ways To Print Blank Line in Python
#using print() for empty lines #using print() with newline character
for empty lines
str = 'latracal Solutions'
s = 'is the best website' str = 'latracal'
s = 'solutions' Output:
Output:
print(str) latracal Solutions latracal Solutions
print() print(str,"\n")
print(s) is the best website print(s) is the best website

#using print() with single quotes for


empty lines #using print() with newline character
with * for multiple empty lines
str = 'latracal' str = 'latracal'
s = 'solutions' s = 'solutions' Output:
Output: latracal
print(str) latracal Solutions print(str)
print('') print(5 * "\n")
print(s) is the best website print(s)

#using print() with single quotes for


solutions
empty lines

str = 'latracal'
s = 'solutions'
Output:
print(str) latracal Solutions
print('')
print(s) is the best website
for loop example

Program to add numbers from 1 to n, where n is input by


user.
n=int(input('Enter +ve integer='))
sum=0
if n>=0:
#upto but not including second argument of range
for i in range(1,n+1):
sum+=i
print('Sum=',sum)
else:
print('Illegal input')
for loop example
Input five numbers from users and find the minimum and
largest number.
# take three numbers from user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
num4 = float(input("Enter third number: "))
num5 = float(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):


largest = num1
elif (num2 > num1) and (num2 > num3): if (num1 < num2) and (num1 < num3):
largest = num2 Minimum = num1
else: elif (num2 < num1) and (num2 < num3):
largest = num3 Minimum = num2
else:
print("The largest number is",largest) Minimum = num3

print("The minimum number is", Minimum)


while loop example
Program to print the number of digits in an integer - no
leading 0s.
i=int (input('Enter an integer:'))
if i<0:
i=-i
noOfDigits=0
if i==0:
noOfDigits=1
else:
while i>0:
noOfDigits+=1
i=i//10
print('No of digits= ',noOfDigits)
Nested for loop
• for loops can be nested within themselves. The syntax
below shows a 1-level nested for loop.
• Example:
for in n:
# piece of code goes here
for in n:
# piece of code goes here

Let’s use the nested for


loop to print the following for i in range(1, 6):
pattern:
# outer loop
for j in range(i):
1 # 1st level inner loop
22 print(i, “ “)
333 print('\n')
4444
55555 To enter into next line To keep space
between numbers
Nested while loop
• for loops can be nested within themselves. The syntax below shows a
1-level nested for loop.
• Syntax:
while condition:
# piece of code goes here
while condition:
# piece of code goes here

i = 0 # initialize to zero for outer loop


Let’s use the nested for j = 0 # initialize to zero for inner loop
loop to print the following As there are 5 lines
pattern: while i <= 5:
# outer loop runs n times
while j < i:
* # inner loop runs i times
** print(‘*’, end=‘ ‘)
*** j += 1 # increment before checking inner loop condition
j=0 # re-initialize after leaving inner loop
**** i += 1 # increment before checking outer loop condition
***** print(‘ ')
To insert empty line
Program-1
• Write a python program to enter a number from user and check whether that
number is prime or not using
• (a) if-else conditions
• (b) for loop.
# To take input from the user
num = int(input("Enter a number: ")) # To take input from the user
# define a flag variable num = int(input("Enter a number: "))
flag = False
# prime numbers are greater than 1
# prime numbers are greater than 1 if num > 1:
if num > 1: # check for factors
# check for factors for i in range(2,num):
for i in range(2, num): if (num % i) == 0:
if (num % i) == 0: print(num,"is not a prime numb
# if factor is found, set flag to er")
True print(i,"times",num//i,"is",nu
flag = True m)
# break out of loop break
break else:
print(num,"is a prime number")
# check if flag is True
if flag: # if input number is less than
print(num, "is not a prime number") # or equal to 1, it is not prime
else: else:
print(num, "is a prime number") print(num,"is not a prime number")
Program-2
• Write a python program print Fibonacci series upto nth term

What is Fibonacci series

HINT: Use if-else conditions and for/while loop


References of Today’s lecture

1. Lecture Slides and Code | Introduction to Computer Science and


Programming in Python | Electrical Engineering and Computer Science |
MIT OpenCourseWare

2. lec3and4.pdf (iitk.ac.in)
Any Queries??
Email ID: [email protected]

You might also like