0

I can't get the code to ask 2 different times for the same input.

I want to get an input that is in the list [1, 2, 4, 8, 16] but all kind of inputs are "valid" for the program. How can I make it that if the first input is wrong (not in the list) I get to ask again for the same input? This is my code so far:

 d = int(input("¿Cuál quieres que sea el valor máximo de duración?\nTen en cuenta que el valor mínimo está definido y es la semicorchea.\n\nSemicorchea = 16\nCorchea = 8\nNegra = 4\nBlanca = 2\nRedonda = 1\n"))

    if d == 16:
        duraciones.append(0.25)
    if d == 8:
        duraciones.append(0.5)
    if d == 4:
        duraciones.append(0.5)
        duraciones.append(1)
    if d == 2:
        duraciones.append(0.5)
        duraciones.append(1)
        duraciones.append(2)
    if d == 1:
        duraciones.append(0.5)
        duraciones.append(1)
        duraciones.append(2)
        duraciones.append(4)
    if d not in [16, 8, 4, 2, 1]:
        int(input("Valor no válido. Debe ser uno de la siguiente lista:\n\nSemicorchea = 16\nCorchea = 8\nNegra = 4\nBlanca = 2\nRedonda = 1"))

(duraciones is another list)

Uahf
  • 9
  • 1

2 Answers2

0

Change your first line to be:

while True:
    d = int(input(.....))
    if d in [16, 8, 4, 2, 1]:
       break

There are other ways to write this code, but this is the closest in spirit to what you've already written.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • This is a very common duplicate. Please vote to close as a duplicate instead of adding an answer. – Pranav Hosangadi Jan 15 '23 at 17:34
  • Sometimes people (especially new programmers) have difficulty knowing what to search for, so answers to their specific questions (though they may be duplicates) can be very helpful to get them on the right path. – ubiquibacon Jan 15 '23 at 17:35
  • Thanks, but that stops my program completely. How can I ask for the same input again with a new message? – Uahf Jan 15 '23 at 17:37
-1

You can use the following code. (sorry I trimmed the input text tht was too large). I initialized the count so that you dont have to enter the first number twice. Hope it helps :)

 ct=0
    d = int(input())
    while d not in [16, 8, 4, 2, 1]:
    if ct!=0:
        d=int(input())
    ct=2
    if d == 16:
        duraciones.append(0.25)
    if d == 8:
        duraciones.append(0.5)
    if d == 4:
        duraciones.append(0.5)
        duraciones.append(1)
    if d == 2:
        duraciones.append(0.5)
        duraciones.append(1)
        duraciones.append(2)
    if d == 1:
        duraciones.append(0.5)
        duraciones.append(1)
        duraciones.append(2)
        duraciones.append(4)
Aditya Singh
  • 135
  • 6