Presentation is loading. Please wait.

Presentation is loading. Please wait.

Hossain Shahriar shahriar@cs.queensu.ca CISC 101: Fall 2011 Hossain Shahriar shahriar@cs.queensu.ca.

Similar presentations


Presentation on theme: "Hossain Shahriar shahriar@cs.queensu.ca CISC 101: Fall 2011 Hossain Shahriar shahriar@cs.queensu.ca."— Presentation transcript:

1 Hossain Shahriar shahriar@cs.queensu.ca
CISC 101: Fall 2011 Hossain Shahriar

2 Announcement and reminder!
Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s) More on range function While loop Break

3 Range function >>> range(5)
[0, 1, 2, 3, 4] # we are getting one less element that expected >>> range(5, 10) [5, 6, 7, 8, 9] # we are getting one less element that expected >>> range(4, 12, 3) [4, 7, 10] >>> range(-10, -100, -30) [-10, -40, -70] Write a program that sum the series: sum =0; For i in range (2, 12, 2): sum+= i

4 While loop while expr1 : statement Two things to keep in mind for using while loop expr1 must include an iterating variable You are responsible for incrementing/decrementing the iterating variable to terminate the loop Let us sum the series: … 10 [watch the red lines!!] sum =0 i=2 while i < 10: sum+= i i+= 2

5 Loop (cont.) – Break statement
Useful in certain situations and often used in an if-else structure within a loop Imagine, we want to iterate a list to find at least one negative number We do not need to continue the loop once we find a case for x in len (list) If x < 0: Print ‘found a negative number, goodbye!’ break Caution: if you have multiple loops, then break will only affect the immediate loop where it is located For …. : #loop1 For … : #loop2 If … break # break loop2 only and loop1 will continue as usual

6 Loop (cont.) – Break statement
Take home assignment: (3 marks) Write a program that checks if a given number N is prime or not. Tips: N is a prime number when it not divisible by any number other than 1 and N You need to use a for/while loop, if-else, and a break statement Iterate from 1 to N/2 and check the remainder is always non zero to conclude that N is a prime number

7 Exception A generic way to handle incompatible input
E.g., a user provides string instead of a number def main(): try: x = int (input ("enter a number : ")) except Exception: print "The supplied input is not a number" main()

8 Tomorrow’s class File handling


Download ppt "Hossain Shahriar shahriar@cs.queensu.ca CISC 101: Fall 2011 Hossain Shahriar shahriar@cs.queensu.ca."

Similar presentations


Ads by Google