-3

Well, I'm pretty new to programming and I need some help with this code.

roundvalue = True
rounds = 0
while roundvalue == True:
 rounds= input("Pick a number of rounds (3 or 5)")
try:
    int(rounds)
except ValueError:
    try:
        float(rounds)
    except ValueError:
        print ("This is not a number")

    if rounds  ==  3:
       print("You chose three rounds!")
       roundvalue = False
    elif rounds == 5:
        print ("You chose 5 rounds")
        roundvalue = False
    else:
        print ("Input again!")

The point of the code is to select a number of rounds and if the user inputs anything else (Letters or numbers that are not 3 or 5) it should repeat the question. *(My code just currently repeats 'Pick a number of rounds (3 or 5)'

Lukas
  • 11
  • 1
  • 1
    Is that your real indenting? – Karoly Horvath Dec 02 '15 at 13:25
  • This may be useful to you: [Asking the user for input until they give a valid response](http://stackoverflow.com/q/23294658/953482) – Kevin Dec 02 '15 at 13:25
  • 1
    Indentation is important in Python. Your while loop as shown is only around the `rounds = ` part, it does not enclose the `try ... except`. Also `int(rounds)` does not change the value of `rounds`, hence even if you enter `3` for `rounds`, `rounds == 3` is always `False` because `rounds` is still a string at this point. Also: why `float(rounds)`? – dhke Dec 02 '15 at 13:26

2 Answers2

0

This will achieve the desired result in a more concise way.

while True:
    rounds = input("Pick a number of rounds (3 or 5)")
    try:
        rounds = int(rounds)
        if rounds in [3,5]:
            break
    except ValueError:
        print("This is not a number")
    print("Input again!")
print ("You chose %d rounds" % rounds)
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
-2

In first try you should put rounds = int(rounds) and in the try below rounds = float(round).

Check this with proper indentations:

roundvalue = True
rounds = 0 
while roundvalue == True:
    rounds= input("Pick a number of rounds (3 or 5)")
    try:
        rounds = int(rounds)
    except ValueError:
        print ("This is not a number")

    if rounds  ==  3:
        print("You chose three rounds!")
        roundvalue = False
    elif rounds == 5:
        print ("You chose 5 rounds")
        roundvalue = False
    else:
        print ("Input again!")
PatNowak
  • 5,721
  • 1
  • 25
  • 31
  • Agree about the ints, but why floats? If not the characters 3 or 5, its invalid according to the OP. No need to check for floats. Also, I'm not sure your indentation is very good. – Mad Physicist Dec 02 '15 at 13:29
  • I pasted, and it corrupted my indent... Now is fine. – PatNowak Dec 02 '15 at 13:36
  • Now your narrative does not correspond with the code... If you fix that and mention the problem with the OP's indentation, you will have a very good answer. – Mad Physicist Dec 02 '15 at 13:45