Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Udacity CS101, Unit 2-26, Equivalent Loops Quiz, Spoiler Alert - My notes after watching the solution to this quiz - Udacity Forums
- This was posted to the Udacity Forum at http://forums.udacity.com/questions/100051420/spoiler-alert-my-notes-after-watching-the-solution-to-this-quiz#cs101
- -----
- print "Udacity Quiz, Lesson 2, Section 26"
- print "The basic 'while' loop"
- print "- Quiz: https://www.udacity.com/course/viewer#!/c-cs101/l-48753036/e-48714355/m-48684618"
- print "- Answer: https://www.udacity.com/course/viewer#!/c-cs101/l-48753036/e-48714355/m-48700404"
- print "A good link regarding 'loop control': break, continue, and pass"
- print "http://www.tutorialspoint.com/python/python_loop_control.htm"
- print ""
- print "The original"
- print "Which of the below produce the same output as this."
- i = 0
- variable1 = 3
- while i <= variable1:
- i = i + 1
- print i
- print""
- print "1. Using 'break'"
- while i <= variable1:
- if False:
- break
- i = i + 1
- print i
- print "This is equivalent because it will never 'break'."
- print""
- print "2. While True"
- print "not equivalent because it prints 1 and then 'breaks'"
- i = 0
- variable1 = 3
- while i <= variable1:
- i = i + 1
- print i
- break
- print""
- print "3. Using 'break'"
- i = 0
- variable1 = 3
- while True:
- if i <= variable1:
- break
- i = i + 1
- print i
- print "This is not equivalent, because in the original the "
- print "command is executed 'while' the test is true."
- print "in this (#3) it 'breaks' if the test is true"
- print "so (in this case) it will not print anything."
- print""
- print "'Correcting' #3. 'if not' "
- print "So now it is equivalent"
- i = 0
- variable1 = 3
- while True:
- if not i <= variable1: # "if i" changed to "if not i"
- break
- i = i + 1
- print i
- print " 'if i <= variable1:' changed to 'if not i <= variable1:' "
- print""
- print "4. Using 'break'"
- i = 0
- variable1 = 3
- while i <= variable1:
- i = i + 1
- print i, "output by main loop"
- if i <= variable1:
- i = i + 1
- print i, "output by 'if' statement in sub-loop"
- else:
- break
- print "This is equivalent, because the 'if statement'"
- print "sub-loop simply does the same work as the main loop"
- print "the main loop prints 1, the sub loop prints 2, then the main loop prints 3"
- print""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement