-1

So i know it might be silly quesion but somehow i can not figure it out. All i want to do is pause loop untill i get valid input from user and ten continue.

So lets say i have a dict:

dict= {'a':'b',
       'c':'d',
       'e':'f'
      }

Now I would like to make a loop that will take a key and print it and wait for users input. If users input equals to key's value then move to another key and if not just repeat as long as input is incorrect.

I know that input pause a loop, but cant figure out how to wait till input is correct before continuing iteration

So loop will print 'a' and wait for users input. If input != 'b' then it will keep asking for input as long as its not a == b . If you get it right it will move to next one and print 'c' and so on

Any help would be appreciated

2 Answers2

1

You can do like this

dict= {'a':'b',
       'c':'d',
       'e':'f'
      }
      
for k, v in dict.items():
    print(k)
    _input = str(input('Enter key:'))
    while _input != v:
        _input = str(input('Enter key:'))
    # your logic from here
Kaushal panchal
  • 435
  • 2
  • 11
0

You can avoid code repetition by using this pattern:

mydict = {
    'a': 'b',
    'c': 'd',
    'e': 'f'
}

for key, value in mydict.items():
    while (text := input(f'Enter the value that corresponds to key {key}: ')) != value:
        print('\aTry again')

Example:

Enter the value that corresponds to key a: b
Enter the value that corresponds to key c: banana
Try again
Enter the value that corresponds to key c: d
Enter the value that corresponds to key e: foo
Try again
Enter the value that corresponds to key e: bar
Try again
Enter the value that corresponds to key e: f
DarkKnight
  • 19,739
  • 3
  • 6
  • 22