Python, not following if statements [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 6 years ago.
I'm trying to create a text bases dungeon game. Just for fun and practice but I'm having a problem with Python not following my if blocks. The weird thing is that it worked when I first typed it out, but a day later it's not. It's treating as if all conditions are true.
choosing_race = True
while choosing_race == True:
print("options: Human, Elf, Dwarf")
p['race'] = input("Choose Race: ",)
print(p['race'], choosing_race)
if p['race'] == "Elf" or "elf":
print()
print("Elves are nimble, both in body and mind, but their form is frail. They gain Bonuses to Intelligence and Dexterity and a Penalty to Constitution")
print()
confirm_race = input("Are you an Elf? ",)
if confirm_race == "yes" or "Yes":
p['int_mod_r'] = 2
p['dex_mod_r'] = 2
p['con_mod_r'] = -2
choosing_race = False
elif confirm_race == "no" or "No":
print()
print("ok, select a different race")
else:
print()
print("Could not confirm, try again")
The p[race] input shows fine, but I can type anything (example duck) and it acts as if I typed elf. When I ask to confirm_race it's always returning yes. I assume I must have put a typo in there, but I can't find it. I redid all my indenting but still no luck. I'm going to try to restructure with functions and maybe that will help. In the mean time I'd love to know what went wrong here so I can prevent it in the future. Thanks. (I'm using Python 3, on my Nexus 5 phone is case that matters)

You are not getting the behavior you expect from lines like
if p['race'] == "Elf" or "elf":
In this case, "elf" evaluates to true every time. You want to instead write
if p['race'] == "Elf" or p['race'] == "elf":
or more concisely
if p['race'] in ["Elf", "elf"]:
or
if p['race'].upper() == "ELF":

Related

Unable to figure out this issue with a choice part of a simple text game im making

What I am trying to get it to do is give an initial choice about a "vial" that the player stumbles across. If the player picks it up, I want it to say something like "you acquired water" and then end. If they say No I just want the code to end so that they can proceed in the game. My trouble comes when I try to account for errors (like if someone puts in a 't' rather than a "Yes" or a "No". I have tried many different models and none of them seem to work. Here is an example of how I want it to behave:
If answer is yes:
You find a vial would you like to pick it up?
y
You have acquired 0.4 oz of water
You continue your journey
If answer is No:
You find a vial would you like to pick it up?
n
You continue your journey
If the answer is invalid:
You find a vial would you like to pick it up?
t
no you really need to decide this
t
You were killed
Game over
would you like to restart this section?
(and then tying in es would restart from the vial question)
My Current code:
keword = False
answer_yes = 'y' and 'yes' and 'Yes'
answer_no = 'n' and 'no' and 'No'
while not keword:
print('water. pick up?')
question = input( )
if question == answer_yes:
print('You have picked up 0.4 oz of water')
answered = True
keword = True
if question == answer_no:
answered = True
keword = True
else:
answered = False
keword = True
while answered == False:
print('no you need to answer')
recon = input( )
if recon == answer_yes:
print('You have picked up 0.4 oz of water')
answered = True
if recon == answer_no:
answered = True
else:
print('You have died the trees ate you. That sucks.')
print('would you like to restart?')
restart = input( )
If any of you have an answer to this that would be cool!
Setting answer_yes to 'y' and 'yes' and 'Yes' will not work, as and is a boolean operator, so it only works with True and False values.
The code you're looking for is:
answer_yes = ['y','yes']
answer_no = ['n','no']
and for your if statements, instead of if question == answer_yes: use if question.lower() in answer_yes.
Enclosing a group of values in square brackets seperated by commas creates a List, and using the in operator checks if a given item exists in a list.
The question.lower() converts it to lowercase, removing the need for including the capitalised versions in the lists.

How do I add an if/else statement with multiple "if" conditions in Python?

I'm trying to create an extremely simple, basic riddle program where Python asks you if you are ready for the riddle, tells you the riddle, checks your answer and repeats.
My problem is I want to create "multiple" answers for the riddle, so it's less case sensitive. Here's my code:
r1Answer = input('')
if r1Answer == 'Silence' # This is where I tried to put my "and" function r1Answer == 'silence' :
print('Correct!')
else:
print('Not quite.')
In Line 2, I've already tried to put an and function in between the two correct answers in my code.
If you want to account for upper or lower you could do the follow:
r1Answer = input('')
if r1Answer.lower() == 'silence': # This is where I tried to put my "and" function r1Answer == 'silence' :
print('Correct!')
else:
print('Not quite.')
the .lower() function will make the string all lower case to keep everything organized...additionally you were missing a : at the end of your if part of your if/else statement, I want ahead and added it.
You can just use a list with all correct answers -
correct_answers = ['ans1', 'ans2']
if answer in correct_answers:
print('Correct')

If statement not working properly inside a while loop [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 3 years ago.
So I'm doing a calculator in python, I have the code for it inside a while loop and a prompt to ask the user if they want to restart the program (that's what the while loop is for) but it does not seem to work properly, am I missing something? I'm kinda new to programming so maybe there is something blatantly wrong that I just don't see. (I did not add the full code but I did import the necessary libraries ("sys" and "math"))
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2 != "yes" or "Yes" or "YES" or "y" or "Y" or "1":
print("\n Ok then, exiting... \n")
sys.exit()
So if the user types, for example, "yes" in the prompt, it should restart the program, but it executes the if statement anyways and closes the program even though the condition for it doesn't apply.
I have tried adding an "else" statement like this:
if var2 != ... :
sys.exit()
else:
print("Restarting...")
But it doesn't seem to work either.
I've also tried doing it the other way around, that is instead of checking if it does not match, check if it does match. Like this:
if var2 == ... :
print("Restarting...")
else:
sys.exit()
But that just gets stuck in the while loop and does not close the program.
I just don't see what's wrong in the code.
The correct way of doing it would be:
if var2.lower() not in ("yes", "1"):
print("Ok then, exiting...")
sys.exit()
You’re logic is backwards you need to exit if it ISNT yes also instead of using or (plus you’re using it incorrectly) use in and instead of typing all the different variations of Yes use star.lower():
var1 = True
while var1 == True:
op = eval(input("\n Your operation: "))
print(f"\n The result would be: {op}")
var2 = input("\n Would you like to do another operation? If so type yes: ")
if var2.lower() not in ("yes", "1"):
print("\n Ok then, exiting... \n")
sys.exit()

How do I assign a function to a variable?

I'm creating a text game so here is the point where I got stuck at:
def characters():
def assassin():
dmg = 150
health = 500
print "Do you want to become an assassin ?"
choice = raw_input("> ")
if choice in ["Yes", "yes", "YES"]:
print "So you said %s about becoming an assassin" % choice
choice = assassin() # Error
else:
print "Templar detected!"
So I wanted to set the choice variable to the assassin() function and then I wanted to copy the properties of the assassin() function to the choice variable but all I get is error that says " assassin is not defined.".
So, how can I do that ?
You have two problems:
if choice == "Yes" or "yes" or "YES": doesn't do what you think it does.
In Python, x or y always returns True or False based on the values of x and y.
The Python intepreter inteprets that line different to how it would be intepreted in English.
It means the same as this if (choice == "Yes") or ("yes") or ("YES").
As a non-empty string has the Boolean value True, this is the same as if (choice == "Yes") or True or True. The first part of that - (choice == "Yes") or True has True as an argument to the or, so it (and therefore the whole line) will always be True.
The second problem is that you are misunderstanding how functions work.
Firstly, neither of these functions do anything. A function is a way of giving a name to some code, which makes your program shorter if you are calling it more than once.
Secondly, variables in a function definition (and functions defined inside others) aren't accessible outside the function. That is why the variable assassin isn't located outside the definition of the characters function.
The assassin function doesn't do anything other than assigning the variables dmg and health some values.

(Beginners Python) Creating if/else statements dependent on user input?

I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.
For example, if I were to say
prompt1=input('Can I make this stupid thing work?')
I would have something along the lines of
if prompt1='yes':
print('Hooray, I can!')
else prompt1='No':
print('Well I did anyway!')
elif prompt1=#an answer that wouldn't be yes or no
#repeat prompt1
I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!
You are pretty close. Read a good tutorial :)
#!python3
while True:
prompt1=input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print('Hooray, I can!')
elif prompt1 == 'no':
print('Well I did anyway!')
else:
print('Huh?') #an answer that wouldn't be yes or no
while True will loop the program forever.
Use == to test for equality.
Use .lower() to make it easier to test for answers regardless of case.
if/elif/elif/.../else is the correct sequence for testing.
Here's a Python 2 version:
#!python2
while True:
prompt1=raw_input('Can I make this stupid thing work?').lower()
if prompt1 == 'yes':
print 'Hooray, I can!'
elif prompt1 == 'no':
print 'Well I did anyway!'
else:
print 'Huh?' #an answer that wouldn't be yes or no
raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
print is a statement instead of a function. Don't use () with it.
Another example, this time as a function.
def prompt1():
answer = raw_input("Can I make this stupid thing work?").lower()
if answer == 'yes' or answer == 'y':
print "Hooray, I can!"
elif answer == 'no' or answer == 'n':
print "Well I did anyway!"
else:
print "You didn't pick yes or no, try again."
prompt1()
prompt1()

Categories