Python Forum
Using Input() in If...Elif Statements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Input() in If...Elif Statements
#11
How would I do that? I am confused about the dictionary part.

Never mind, the dictionary part makes sense. How would I make the function without checking if the input is either hunt or heal?
Reply
#12
Following is an example how this particular problem could be solved. However, it will not address problem which is created by 'What would you like to do' part in 'hunt'.

answers = {'heal': 'Your health is restored!',
           'hunt': 'You encountered a slime! What would you like to do?'}

def validate(question, allowed=answers):
    while True:
        answer = input(question)
        if answer not in allowed:
            print(f"Answer must be one of: {', '.join(allowed)}")
        else:
            return answer
    

print(answers[validate("What would you like to do? ")])
EDIT: with Python 3.8 one can shorten function with walrus operator:

def validate(question, allowed=answers):
    while (answer := input(question)) not in allowed:
        print(f"Answer must be one of: {', '.join(allowed)}")
    return answer
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Whats the right way to refactor this Big if/elif/elif ? pitosalas 1 2,842 Jul-28-2019, 05:52 PM
Last Post: ichabod801
  an input error or elif error , how can i fix this the_fire_pharaoh 1 2,948 Dec-15-2018, 09:47 PM
Last Post: Gribouillis
  Unexpected input within an if/elif statement fier259 2 3,767 May-12-2018, 07:41 AM
Last Post: buran
  input issue elif jge047 2 3,889 Nov-23-2017, 06:29 AM
Last Post: zykbee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020