Preview

10 - For Loops

 1. In a 'for' loop the start and stopping condition …
Note: the following video from www.teachyourselfpython.com provides a beginner's introduction to for loops. Do watch it if possible

  is not defined

  is defined at the end

  is defined in the middle of the loop

  is defined at the start

 2. The following for loop produces an output that starts at 0 and goes up to 95. How could you make it go up to 100.
def main():
  for i in range(0,100,5):
    print(i)

main()

  This cannot be done as for loops only go up to a maximum of 95

  Change line 3 to : print (i:100)

  Change line 2 to: for i in range(200,5):

  Change line 2 to: for i in range(0,105,5):

 3. The following code will produce an output that starts at 1 and goes up to 100
def main():
  for i in range(11):
    print(i)
  
main()

  FALSE

  TRUE

 4. The following code will produce an output that starts at 1 and goes up to 20.
def main():
  for i in range(1,20):
    print(i)
  
main()

  FALSE

  TRUE

 5. How would you adapt this code so that it starts at 3 and goes down to 0 (e.g. 3,2,1,0)
def main():
  for i in range(3,20):
    print(i)

main()

  Change the for loop to: for i in range(-1,3,0)

  Change the for loop to: for I in range(-0,-3,1)

  Change the for loop to: for i in range(3,-1,-1):

  Change the for loop to: for i in range(3,-0,-1):

 6. For loops are useful for iterating(looping) through lists. The following will produce an output of:
def main():
  mylist=["smarties","toblerone","nestle milk","cadburys"]
  for i in range (len(mylist)-1):
    print(mylist[i])
  
main()

  smarties,toblerone,nestle milk, cadburys

  smarties, toblerone, nestle milk

  nestle milk, toblerone, smarties

  smarties, toblerone

 7. Change a bit of the code to make it print just three lines of stars with 20 stars each
def main():
  for i in range(10):
    print("*******")

main()

  for i in range(3): print("********************")

  for i in range(20): print(3)")

  for i in range(3):

  All of the above would work

 8. What is the output of the following code?
def main():
  for i in range(5):
    print(i+1)
main()

  1,2,3

  5,6,7,8

  5,7,9

  1,2,3,4,5

 9. What do the following two functions produce as an output?
def forloop():
  for i in range(5):
    print(i+1)


def whileloop():
  i=1
  while i<6:
    print(i)
    i=i+1

  The for loop produces an output of 1 to 6 and the for loop does the same

  The for loop produces an output of 5,4,3,2,1 and the while loop 1,2,3,4,5,6

  The for loop produces an output of 0,1,2,3,4,5 and the while loop prints 1 to 6

  Both loops produce an output of 1,2,3,4,5

 10. In a for loop the ____________ condition is decided at the start but in a while loop you need to increment/decrement to reach the stopping condition

  start and stop

  0 and 10

  trial and error

  None of the above