-1

Im working on a program that asks the user to enter input twelve times. Those inputs must be included in a list in which there are included the first twelve letters of the alphabet.

letters=("A","B","C","D","E","F","G","H","I","J","K","L")

def gen_():

    s = []

    for i in range(1, 13):

        in_ = input("Input the note number " + str(i) + ", please\n", )

        if in_ in letters:

          s.append(in_)

          print(" \n"+str(s)+"\n " )

        else:

          print("not valid")

gen_()

I would like to tell the program that if a certain input is not valid, it should ask the user to try again and enter a valid input on that same instance. I tried setting "i" back to the value in which the input was not valid, by subtracting 1 to i, but it didn´t work.

How can I code this? Thanks

Germán
  • 65
  • 7
  • 1
    Think about when you want to stop. You don't want to stop after 13 inputs, that's a very narrow use case of "everything went right". You want to stop when you've received 13 valid inputs. In other words: While you *don't* have enough valid inputs, you want keep asking. Potentially forever. Now: you are already storing these inputs, why not use that to know when to stop? – Reut Sharabani Apr 30 '19 at 19:40
  • Why the [generator] tag? – Fred Larson Apr 30 '19 at 19:40

2 Answers2

1

You need a while loop to continuously verify if the entered input is valid. Please check this solution:

def gen():
    s = []
    for i in range(12):
        in_ = input("Input the note number {i}, please: ".format(i=i))
        while len(in_) != 1 or ord(in_) < 65 or ord(in_) > 76:
            in_ = input("Invalid input, please enter again: ")
        s.append(in_)
    return s

I made some tweaks in the while loop to check for the ASCII values of the character entered instead of looking in a predefined tuple/list.

mbhargav294
  • 389
  • 1
  • 3
  • 15
0

The reason why subtracting 1 from i probably didn't work is because python doesn't work like other programming languages where you can modify the index variable inside the for loop and it will react accordingly. To put it very simple since I don't want to get into details, any changes you make to i inside the loop won't change what value i will have in the next iteration.

One way to do what you're trying to do is to write a while loop that repeats as long as the user is giving an invalid input. Something like this:

in_ = input("Input the note number " + str(i) + ", please\n", )
while in_ not in letters:
    print("not valid")
    in_ = input("Input the note number " + str(i) + ", please\n")
s.append(in_)
print(" \n"+str(s)+"\n " )
mbhargav294
  • 389
  • 1
  • 3
  • 15