Preview

10 - For Loops

 1. Any counter-controlled loop (For Loop) can also be implemented with a condition-controlled loop(while loop)

  False

  True

 2. The following program asks the user to guess the number, but in this case only allows two guesses and then the program stops. Can you fix the problem to allow up to 10 guesses?
def main():
    secretnumber= int(input("I'm thinking of a number from 1 - 10, can you guess what it is?: "))
    attempts=0
    for i in range(0,2):
        if secretnumber ==7:
            print("Well done! You guessed the number in ",attempts+1," attempt[s]!")
            break
        else:  # Here only if guess != *is not equal to* password. You don't need to explain the condition again
            print("Try again!")
            attempts += 1 # if somebody gets the password wrong the try again string prints 8 times
            #        ^    ^ You need comment, ''' means string
            #        ^ syntax to increase by 1
        secretnumber = int(input("Enter a guess again:"))  # Ask user for new password each time the user gets it wrong

main()

  attempts = 0 should be deleted

  attempts = 0 should be attempts = 10

  for i in range(0,2) allows 2 guesses and needs to changed to: for i in range(10,0):

  for i in range(0,2) actually allows 3 guesses - it needs to changed to: for i in range(0,9):

 3. The following program, when run with the user entering '2', would produce just one line of output. What would you need to change to get it to print three lines of output, like shown below (times table up with an output of 0,2,4)
def main():
    number=int(input("Enter a number : "))
    
    for i in range(0,1):
        print(number,"times:", i, "is equal to:", i*number)        
        
main()

(2, 'times:', 0, 'is equal to:', 0)


#Enter a number :  2
#(2, 'times:', 0, 'is equal to:', 0)
#2, 'times:', 1, 'is equal to:', 2)
#(2, 'times:', 2, 'is equal to:', 4)

  This cannot be done with a for loop

  Change line 4 to: for i in range(0,3)

  Change line 4 to: for 2 in range (0,1,4)

  Change line 4 to: for i in range (0,4)

 4. This program uses a for loop to execute the famous Fibonacci sequence. The output will be:
a = 1
b = 1
for c in range(1,5):
    print (a)
    n = a + b
    a = b
    b = n
print ("")

  0,1,2,3,4

  0,1,2,3,5

  1 1 2 3

  1 1 2 3 5

 5. What will the output of the following be?
fruits = ['banana', 'apple',  'mango', 'pear']
for fruit in fruits:        
   print (fruit)

  banana,apple,mango,pear

  Error: you cannot use a for loop to iterate through strings in a list

  1,2,3,4

  4

 6. Can you change the code in the for loop below to make it start at 2, stop at 20 and go up by 2 each time. e.g. 2,4,6,8...etc
def main():
  for i in range(0,100,5):
    print(i)

main()

  Line 2 changed to: for 2 in range(0,100,2):

  Line 2 changed to: for i in range(2,20,2):

  Line 2 changed to: for i in range(20,2):

  Line 2 changed to: for i in range(2,21,2):

 7. The following program will output: smarties, toblerone, nestle milk. Why does it leave out the last delicious item in the list?
def main():
  mylist=["smarties","toblerone","nestle milk","cadburys"]
  for i in range (len(mylist)-1):
    print(mylist[i])
  
main()

  because the for loop in line 3 is looking at a range, and it auto-selects the first three

  because the list has four elements, and the for loop is starting at a range of four

  because in line 3 the range (stopping number) is specified as the length of the list -1

  because a for loop never prints the last item in a list - it is better to use a while loop

 8. Nested loops are used for iterating 2D arrays like the 2d array a below. The below code shows that the first loop iterates through the ___________, the second loop runs through the elements __________ of a row.
#Why don't you try it yourself and see how it works

a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
for i in range(len(a)):
    for j in range(len(a[i])):
        print(a[i][j], end=' ')
    print()
	
>>OUTPUT
1 2 3 4 
5 6 
7 8 9 

  row number / outside

  column number / inside

  column number / outside

  row number / inside

 9. what will the output of the following code be?
for i in range(1, 10):
        print (str(i) * i)
		
#Output 1
123456789


#Output 2
1
10
20
30
40
50
60
70
80
90

#Output 3
1
2
3
4
5
6
7
8
9

#Output 4
1
22
333
4444
55555
666666
7777777
88888888
999999999

  Output 2

  Output 1

  Output 4

  Output 3

 10. A nested loop is a loop within a loop. What is the output of the following?
for x in range(1, 3):
    for y in range(1, 3):
        print (x, "x", y, "=", x*y)
		

#Output 1
1 x 1 = 1
1 x 2 = 2
2 x 1 = 2
2 x 2 = 4

#Output 2
(1, x 3, '=', 1)
(1, x 4, '=', 2)
(2, x 5, '=', 2)
(2, x 6, '=', 4)

#Output 3
(1, x 1, '=', 1)
(2, x 2, '=', 4)
(3, x 3, '=', 9)
(4, x 4, '=', 16)

  Output 3

  None of these options apply

  Output 2

  Output 1