control structure
play

Control structure: Repetition - Part 3 01204111 Computers and - PowerPoint PPT Presentation

Control structure: Repetition - Part 3 01204111 Computers and Programming Cha hale lermsak Cha hatdokmaip ipra rai De Depart rtment of of Com omputer r Eng ngineerin ing Kas asetsart Uni niversity Revised 2018-07-18 Cliparts are


  1. Control structure: Repetition - Part 3 01204111 Computers and Programming Cha hale lermsak Cha hatdokmaip ipra rai De Depart rtment of of Com omputer r Eng ngineerin ing Kas asetsart Uni niversity Revised 2018-07-18 Cliparts are taken from http://openclipart.org

  2. Outline ➢ A Loop Pattern : Loop and a Half ➢ A Loop Pattern : Forever Loops with break ➢ A Loop Pattern : Nested Loops 2

  3. 3

  4. What is the loop and a half ? ➢ The loop and a half is a loop that may exit (on a special condition) somewhere in the middle of the loop body. ➢ Such premature loop exit could be done by the return statement, or the break statement, or the continue statement. ➢ We will not cover continue in this course, though. It’s quite handy in simple programs but can make more complex programs harder to comprehend, so some purist programmers tend to avoid using it. 4

  5. Loop and a half with the return statement Recall that executing the return statement causes the running Pre-loop statements function to exit and go back to the caller. F loop condition Whenever this special exit condition T becomes true at an iteration, the return early loop body statement will get executed, causing an immediate return to the caller. F special exit condition T Go back to return the caller The immediate return causes the The rest of loop body rest of the loop body to be skipped at the last iteration. Thus the name “ the loop and a half ”. 5

  6. Task: Finding a Character in a String ➢ Write a function find ( text , char , index ) such that: • It scans the string text starting at the string index index , searching for the first occurrence of the character char . The default index is 0. • If char is found, it returns the index of text where char is. • If char is not found, it returns -1 6

  7. Task: Finding a Character in a String We want the function find() to behave like this: Exactly the same as the previous call since the default starting >>> find('Que sera, sera', 'e', 0) index is 0. 2 >>> find('Que sera, sera', 'e') 2 >>> find('Que sera, sera', 'Q') >>> find('Que sera, sera', 'e', 2) 0 2 >>> find('Que sera, sera', 'q') >>> find('Que sera, sera', 'e', 3) -1 5 >>> find('Que sera, sera', ',') >>> find('Que sera, sera', 'e', 6) 8 11 >>> find('', 's') >>> find('Que sera, sera', 'e', 12) -1 -1 >>> 7

  8. The function find () - Algorithm Let’s try to figure out what find() should do for this call. >>> find('Que sera, sera', 'e', 3) These repeated The three parameters : actions suggests text is 'Que sera, sera' char is 'e' a loop algorithm index is 3 index is 3 and text [ index ] != char , The loop is to scan so increment index by 1 to become 4 text searching for char, so it should index is 4 and text [ index ] != char , iterate over the so increment index by 1 to become 5 indexes of text. index is 5 and text [ index ] == char , so char has been found , return index Therefore Whenever char is found within text, text[index] == char the loop immediately exits via return is the special exit with the current index. condition. 8

  9. find () : from algorithm to code The three parameters : text is 'Que sera, sera' A loop-and-a-half char is 'e' algorithm index is 3 index is 3 and text [ index ] != char , so increment index by 1 to become 4 The default index is 4 and text [ index ] != char , starting index so increment index by 1 to become 5 index is 5 and text [ index ] == char , The loop iterates so char has been found , return index over the indexes def find( text , char , index = 0 ): of text. Each iteration textlength = len ( text ) keeps looking while index < textlength : for char within Normal exit if text [ index ] == char : text. of the loop return index means char is not found index = index + 1 in text. return - 1 9

  10. The Function find () - finished def find( text , char , index = 0 ): """finds the 1st occurrence of <char> within <text>, starting scanning at <index> (default at 0) returns the index of <char> in <text> or -1 if not found """ textlength = len ( text ) while index < textlength : if text [ index ] == char : return index index = index + 1 return - 1 10

  11. for loop and a half ➢ The loop-and-a-half with the return statement can be implemented by the for statement as well. As an example, let’s implement a much simpler, scaled down version of find() . Call it the function has_char() which runs like this: has_char() requires two parameters: >>> has_char('Que sera, sera', 'e') a string and a character . True It returns True if >>> has_char('Que sera, sera', '3') the string contains False the character at least once, or False otherwise. 11

  12. The Function has_char () - Code has_char() can use the def find( text , char , index = 0 ): same algorithm as textlength = len ( text ) find() , except that it while index < textlength : doesn't have to care if text [ index ] == char : about the indexes at all. return index index = index + 1 return - 1 Thus, a for loop suffices. def has_char( text , char ): """returns True if there is the character <char> in the string <text> or False otherwise""" A for loop containing for c in text : a return statement is if c == char : also a loop and half . return True return False 12

  13. 13

  14. Loop and a half with the break statement Executing the break statement Pre-loop statements terminates the loop in which it is contained, and transfers control to the code immediately following F loop condition the loop. T Whenever this special exit condition early loop body becomes true at an iteration, the break statement will get executed, causing F special exit an immediate break out of the loop. condition T Go to the first statement break following the loop. The immediate break causes the The rest of loop body rest of the loop body to be skipped at the last iteration. Thus the so- called “ loop and a half ”. 14

  15. find () - Alternative Version Using break def find( text , char , index = 0 ): #version 1 Instead of the immediate textlength = len ( text ) return here, it can break while index < textlength : out of the loop first and if text [ index ] == char : then return the result return index after the loop. index = index + 1 Both versions work return - 1 effectively the same. def find (text, char, index=0): #version 2 First, initialize the result to the result = -1 not found status. textlength = len(text) while index < textlength: Whenever char is found, the if text[index] == char: current index is the result, then break out of the loop. result = index break Notice that if char is never index = index + 1 found in text , the loop will exit normally and result return result remains to be -1. 15

  16. has_char () - Alternative Version Using break Instead of the immediate def has_char( text , char ): #version 1 return here, it can break for c in text : out of the loop first and if c == char : then return the result after the loop. return True return False Both versions work effectively the same. def has_char (text, char): #version 2 First, initialize the result to result = False False (the not found status). for c in text: Whenever char is found, if c == char: set result to True (the result = True found status), then break break out of the loop. return result Notice that if char is never found in text , the loop will exit normally and result remains to be False. 16

  17. 17

  18. The Forever Loop ➢ Some algorithms call for a loop that repeats its body unconditionally , ie. without a loop condition. Thus, the so-called forever loop that repeats forever ! ➢ The forever loop with break is a more sensible kind of the forever loop . Though it has no loop condition to check before each iteration, it may exit on a specified exit condition somewhere in the middle of the loop body. ➢ Therefore the forever loop with break is a special, simple kind of the loop and a half . 18

  19. The Forever Loop with break is not forever. Without any loop condtion, Pre-loop statements the loop body is repeated unconditionally, thus the term "forever loop" Whenever this exit condition becomes early loop body true at an iteration, the break statement will get executed, causing F exit an immediate break out of the loop. condition T Go to the first statement break following the loop. The immediate break causes the The rest of loop body rest of the loop body to be skipped at the last iteration. 19

  20. The Forever Loop with break in Python Since the loop condition True is always true, the Pre-loop statements loop repeats forever. pre-loop statements early loop body while True: F exit early loop body condition if exit_condition == True T break break the rest of loop body This break upon exit_condition The rest of loop body makes it possible for the loop to terminate eventually. 20

  21. A Simple Example Can you figure out print('Hi there.') from the code what while True: this program does? s = input('Enter something: ') if s == 'quit': break print(f'You entered {len(s)} characters') print('Bye now.') Hi there. Enter something: python You entered 6 characters Enter something: Time flies. An empty line You entered 11 characters is entered. Enter something: You entered 0 characters This word hits the Enter something: quit exit condition. Bye now. >>> 21

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend