1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Can't raise an exception with user input

Discussão em 'Python' iniciado por Stack, Outubro 4, 2024 às 19:03.

  1. Stack

    Stack Membro Participativo

    I want to raise an exception in this bit of code when the user enters a choice that's not in my 3 specified choices:

    inventory = []
    print "You can choose 2 items from the following:"
    print "Gun, Grenade, Smoke bomb. Type your weapon choices now: "

    try:
    choice1 = raw_input("Choice 1: ")
    inventory.append(choice1)

    except:
    if choice1 not in ('gun', 'grenade', 'smoke bomb'):
    raise Exception("Please enter one of the 3 choices only only")


    However, when I run it, the users choice will be accepted no matter what they type in and I'm not clear why.

    I know I can make this work with other ways such as putting a while loop after the raw_input to check what was entered against those 3 items but I want to do this with try and except.

    Continue reading...

Compartilhe esta Página