+ 1
Python if else error
I'm trying to get python to be able to respond to more than one input at a time. I know I can do it if I individually go line by line and put if If x == blah Print: ("blah") But I wonder if i can create a list on one line for it to respond to so I wont have to tediously go line by line. For example If x == "blah", "blah", "blah" Print ("blah") Else: Print ("blah") But that gives me a syntax error because it doesn't like that I'm using the commas to separate the possible inputs. Is there a way for me to use multiple I puts in one 'if' line? Thanks. Below is the code I'm referring to. https://code.sololearn.com/chTUQk35bNFR/?ref=app
4 ответов
+ 4
You can also do it this way 😎
a = input("Type one of the following words: Yes, yes, yeah, Yeah, yep, Yep, yup, or Yup\n")
print(f'Input{" " if a in ("Yes", "yes", "Yeah", "yeah", "yup", "yep", "Yep", "Yup") else " not "}accepted.')
+ 6
To make the code more DRY (Don't Repeat Yourself), you can also do it this way
words = ("Yes", "yes", "Yeah", "yeah", "yup", "yep", "Yep", "Yup")
a = input(f"Type one of the following words: {words}\n")
print(f'Input{" " if a in words else " not "}accepted.')
+ 3
#You can use the same method you had by separating them with commas, but you'll need to replace the equals operator with "in" and then add parantheses around the options (indicates a tuple-which is essentially an immutable list) which is saying “if the user input is in this tuple, then:”
a = input()
if a.lower() in ["yes", "yeah", "yup", "yep"].lower():
print ("input accepted")
else:
print ("not accepted")
#the .lower method will allow user input of those 4 words in any case (yes,yEs,YES..etc) as the options in the tuple are lowercase and a.lower() will convert the user input to lower case, so its comparing lowercase to lowercase
+ 1
Yeah I just checked it again and it makes it accept every input regardless of what it is lol. I'll run through it again when I'm not mentally exausted. Thanks