1

Here's a small text based RPG I'm making to start programming in Python:

#global variables
cpu = "[WOPR] "

print("%sLet's play a game within Python 3.4.\n\n%sWhat is your name User?" % (cpu, cpu))
#this is the first question 
q1 = str.lower(input("Would you like to tell %s your name?\n" % cpu))
if q1 == 'yes' or q1 == 'yeah' or q1 == 'ok' or q1 == 'okay' or q1 == 'alright' or q1 == 'y':
    name = input("What is your name?\n")
    user = "(%s) " % name
elif q1 == 'no' or q1 == 'nah' or q1 == 'nope' or q1 == 'n':
    print("%sAlright I'll just call you Scrub from now on" % cpu) 
    name = "Scrub"
    user = "(%s) " % name
else: #this is just a catch all, will cause an error if this activates(so it ends the script)
    print("u dun messed up m8")

Is there's a way to shorten

if q1 == 'yes' or q1 == 'yeah' or q1 == 'ok' or q1 == 'okay' or q1 == 'alright' or q1 == 'y':

to something a bit less bulky ( I tried if q1 == 'yes' or 'yeah' etc. but it didn't work).

It's a bit annoying to have to type all those things over and over again any time I want to ask a yes or no question, but I'd like to have all the options there so that it accepts all variations of yes or no.

I found Python 3 input and if statement but didn't see anything about shortening the line of code, only about how to fix the problem that he had.

Community
  • 1
  • 1
DaftKitteh
  • 41
  • 5
  • You could use: `if q1 in ['yes', 'yeah','ok','alright','y']:` – logic Apr 10 '15 at 17:33
  • [How do I test one variable against multiple values?](https://stackoverflow.com/q/15112125) is the canonical for the part you tried and didn't work. Since it also answers your question on how to shorten the expression, I have duped your post to that one. – Martijn Pieters Apr 10 '15 at 17:33

1 Answers1

0

You can use in to test for membership:

if q1 in {'yes', 'yeah','ok', 'okay' ,'alright', 'y'}

You can also call lower on input:

q1 = input("Would you like to tell %s your name?\n" % cpu).lower()
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321