0

I am trying to create a function where the user guesses a letter; but I made it complicated and now, after guessing the correct letter, the loop doesn't break.

di = {1:"a", 2:"b", 3:"c", 4:"d"}

number = random.randint(1,4)

while True:
    guess = input("Enter alpha")
     
    for i in range(1,len(di)+1):
        if guess in di[i]:
            if i == number:
                print("correct")
                break
             
            elif i > number:
                print("large")
            else:
                print("small") 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Mayank S
  • 11
  • 1
  • 2
  • Do you mean "a randomly generated character"? Alphabet is a set of all characters. – DYZ Aug 09 '20 at 07:09
  • @DYZ I'm not sure this is a duplicate of the question linked- I think OP is trying to understand why his break statement is not breaking out of the "while True" loop. – Josh Honig Aug 09 '20 at 07:12

1 Answers1

0

the break is breaking the for loop. In case you want to break while loop, it can be done this way:

import random

di = {1:"a", 2:"b", 3:"c", 4:"d"}

number = random.randint(1,4)

while True:
    guess = input("Enter alpha")
    status = False     
    for i in range(1,len(di)+1):
        if guess in di[i]:
            print(i,number)
            if i == number:
                print("correct")
                status = True
                break
             
            elif i > number:
                print("large")
            else:
                print("small") 
    if status:
        break
rrr.code9
  • 1
  • 1
  • thank you for sharing knowledge. – Mayank S Aug 09 '20 at 07:28
  • @MayankS when the condition i == number satisfies, the for loop breaks, however the while loop continues. in order to break the while loop the status flag is changed to True before breaking the for loop. Then once the for loop breaks the status is checked after the for loop (inside while loop) and if status is True then it breaks while loop. – rrr.code9 Aug 09 '20 at 07:33
  • @ rrr.code9 again thanks a ton for explaining this. – Mayank S Aug 09 '20 at 07:46