Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2017-2018 KH (24/10/17) Lecture 11: while loops 2017-2018 1 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 2 / 1 for loop revisited while loop Syntax For loop is generally used where number of iterations (repetitions) is known in advance for i in range(n + 1): total = total + i What if we don t know this number? Components while condition : body Condition Boolean condition Loop body Indented block of statements Meaning Condition controls loop execution Repeatedly execute loop body but check that condition is True before each repetition; terminate loop if condition is False KH (24/10/17) Lecture 11: while loops 2017-2018 3 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 4 / 1
while loop cont d A concrete example while condition : body 1 Evaluate condition: if False skip to Step 4 otherwise proceed to Step 2 2 Execute loop body 3 Go back to Step 1 4 (Continue execution with statement following the while) Task Read in a series of positive numbers one per line and output their sum; series terminated by 1 (not part of series) e.g. Terminology Ideas 1 17 5 1 23 The 1 is known as a sentinel No predetermined indication of length of series Use while loop: condition captures have we reached the end of the series? KH (24/10/17) Lecture 11: while loops 2017-2018 5 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 6 / 1 Solution num = int(input( Please enter a number: )) while num!= 1: num = int(input( Please enter a number: )) print( Total is, total ) Solution cont d while num!= 1: num = int(input( Please...: )) print ( Total is, total ) Trace of program execution for series: 1 17 5 1 num =... (reads 1) num!= -1? (True) (now 1) num =... (read 17) num!= -1? (True) (now 18) num =... (reads 5) num!= -1? (True) (now 23) num =... (reads -1) KH (24/10/17) Lecture 11: while loops 2017-2018 7 / 1 num!= -1? (False) print Note: Loop execution interleaves condition check and execute body steps KH (24/10/17) Lecture 11: while loops 2017-2018 8 / 1
Solution cont d A variation on the theme while num!= 1: An alternative to the sentinel approach is the go-around option. Ask the user after each number whether it is the last print ( Total is, total ) KH (24/10/17) Lecture 11: while loops 2017-2018 9 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 10 / 1 Another solution Another solution cont d done = False while not done: num = int(input( Please enter a number: )) go again = input( Would you like another (y/n)? ) done = go again. strip ()!= y print( total was, total ) Statement done =... controls loop Variable done transmits it done = False while not done: go again = input( Would...? ) done = go again. strip ()!= y print ( total was, total ) Performs at least one iteration Execution sequence: Execute body Check if finished Execute body Check if finished Execute body Check if finished etc. Effectively check happens at the end of each loop body execution rather than the start KH (24/10/17) Lecture 11: while loops 2017-2018 11 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 12 / 1
for loops vs while loops Syracuse sequence Can always re-write for loops using while for n in range(20, 10, 2): total = total + n print( total ) n = 20 while n > 10: total = total + n n = n 2 print( total ) while is more powerful, but can be harder to work with General rule: Favour for loops for definite iteration i.e. where number of iterations known in advance and while loops otherwise The Syracuse sequence is generated by starting with a natural numbers and repeatedly applying the following function until 1 is reached: { x/2 if x even syr(x) = 3x + 1 if x odd Example (n = 5): 5, 16, 8, 4, 2, 1 Task: Write a program that generates the Syracuse sequence for a given value of n KH (24/10/17) Lecture 11: while loops 2017-2018 13 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 14 / 1 Syracuse function Generating Syracuse series def syr(x): if x % 2 == 0: return x // 2 else : return 3 x + 1 current = n print(current, :, end = ) while current!= 1: current = syr(current) print(current,, end = ) print() Wrap a for loop around this to generate series for values 1 to 20 say. KH (24/10/17) Lecture 11: while loops 2017-2018 15 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 16 / 1
Prime numbers Testing for primality A whole number is prime if it has no divisors other than itself and one Examples: primes 2, 3, 5, 7, 11, 13, (infinitely many) non primes 4, 10, 34 Task: Write a Python function that determines whether a given number is prime or not Idea: Try candidate divisors 2, 3, 4,, n 1 in turn to see if any divide number evenly; if none do then n is prime, otherwise not def is prime (n): # Return True if ' n' is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors and n % cand!= 0 cand = cand + 1 return no divisors KH (24/10/17) Lecture 11: while loops 2017-2018 17 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 18 / 1 Testing for primality cont d Goldbach s Conjecture def is prime (n): # Return True if n is prime no divisors = n > 1 cand = 2 while no divisors and cand < n: no divisors = no divisors \ and n % cand!= 0 cand = cand + 1 return no divisors Easy to see function produces correct answer for {0, 1, 2} Variable cand steps through values 2, 3, 4,, n 1 in turn If divisor found, variable no divisors set to False Once False, value can never revert to True The conjecture Every even integer greater than two can be expressed as the sum of two primes Believed to be true, but no known proof Task Verify the conjecture for integers up to 200 Idea For specific number n and value i, see if i and n i are both prime Try each possible i from 2 upwards, until you find a pair that works KH (24/10/17) Lecture 11: while loops 2017-2018 19 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 20 / 1
Back Material Solution Notes and Acknowledgements print(k, :, end = ) for i in range(2, k): if is prime ( i ) and is prime(k i): print(str( i ), +, str(k i), end = ) break print() Wrap a for loop around this to repeat this for even values of k in the range 4 to 200 (say) Reading Code Acknowledgements KH (24/10/17) Lecture 11: while loops 2017-2018 21 / 1 KH (24/10/17) Lecture 11: while loops 2017-2018 22 / 1