If statement not working properly inside a while loop [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)
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()

Related

Struggling with loops and statements

So I've almost finished a calculator but after giving the results, I want it to ask if I'm still gonna use it.
At the beginning of the code I have this loop to make it start again unless I typed 'n'.
# LOOP TO MAKE IT STAY ON
import sys
from colorama import init
from colorama import Fore, Back, Style
init()
while True:
Then the rest of the code which is finished goes on.
Then, at the end, I've tried this:
answer = input()
def badanswer():
if answer != "y" or "n":
return True
else:
return False
while badanswer is True:
print ("Wrong answer")
answer = input(("Wanna keep using the calculator? y/n "))
if badanswer is False:
if answer == "y":
continue
else:
break
sys.exit()
Somehow when I test it I type a random letter (not y or n) and the program continues... What I am missing here? I'm pretty new to python so forgive my mistakes! Thanks.
One problem is the
if answer != "y" or "n":
"or" is a logical operator, and does not allow you to "double" a != comparison like you are trying to do. The actual meaning of this statement is if answer is not "y", or if "n", and "n", like any nonempty string, is always True in boolean context.
You want
if answer not in ("y", "n"):
You also need to actually call badanswer() by adding the parentheses.
There's also no reason to add the if True to the loop condition — while badanswer() does the same thing.
badanswer is a function, not a boolean. You need to call the function and get its return value, like so: if badanswer() is True
However, your logic for exiting the program is needlessly contrived. You don't need the badanswer function at all. Just get the input from the user and check whether it is 'y' or 'n'.
while True: # loop for exit prompt
answer = input("Wanna keep using the calculator? y/n ").lower()
# using .lower() to permit 'Y' and 'N' as well
if answer == "n":
sys.exit()
elif answer == "y":
break
# exits from the 'exit prompt' loop,
# returns to the outside calculator loop
else:
print("Bad answer!")
Note: As mentioned in the comments, sys.exit() is a pretty cutthroat way to exit your program. You can do it more gracefully by modifying a variable that is checked by the outer calculator loop; e.g., initialize a variable keep_running = True, run the main loop with while keep_running: (...) and if the user requests to exit from the calculator, set keep_running = False so that the main loop exits.

I can't break this while loop

I have an assignment where I need to complete an action until the input is 'quit', 'Quit', 'q', or 'Q'. I've been trying this:
while variable != 'quit' or 'Quit' or 'q' or 'Q':
# do stuff
however when any of those strings are inputted the while loop still executes! I've tried other ways like if statements but it just times out. How can I break the loop correctly?
The way to go is probably something like this:
while str(variable).upper() not in ['QUIT', 'Q']:
This way, you can list all the values which allow the user to quit in one place and the case (upper or lower) is ignored.
If I'm understanding this correctly, you have something like the following:
while variable != 'quit' or 'Quit' or 'q' or 'Q':
# do stuff
variable = input("")
(By the way - welcome to Stack Overflow! As another user has mentioned in a comment - please provide a code example; it will help potential answerers actually know what's going wrong and what you're trying to do.)
The reason why it never breaks is because what the Python interpreter actually sees is:
while (variable != 'quit') or ('Quit') or ('q') or ('Q'):
# do stuff
variable = input("")
In Python, non-empty strings will evaluate to true - if you try bool('q') in the Python interpreter, you will get True. This means that the interpreter is running:
while (variable != 'quit') or True or True or True:
# do stuff
variable = input("")
which obviously never breaks. What you need to do is check all options; Kind Stranger has one solution but more explicitly, you could try
while variable not in ('quit', 'Quit', 'q', 'Q'):
Try this:
while (variable != "quit" and variable != "q" and variable != "Q" and variable != "Quit"):
You cannot do variable != "q" or "Q" etc.

How to re-run the program and ask for concussive inputs [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
This seems kind of simple but for the life of me I have no idea on how to even approach this
At the end of my code, I have a
if(__name__ == "__main__"):
block
And after that line I ask for the users input for something and I execute my function kind of like so
b = input("enter something")
run_my_func(b)
And right now it just ends right there.
How can I make it so that it will again ask for an input or exit of the user inputs nothing and presses enter
My initial idea was to put it in a while loop? But I'm not sure if that'd work/how to implement it
Yes, you can use a while loop. Because you need to check a condition (empty user input) right in the middle of the loop to decide when to stop, there's a standard trick for this. You write a while True loop which runs forever by default, and then you use break statement when the condition is met to end the loop early:
while True:
b = input("enter something: ")
if b == "":
break
run_my_func(b)
A while loop would be a great way to implement what you are trying to do. Below is an example:
functional = True
while functional:
userInput = input("enter something")
if userInput == "":
functional = False
else:
print(userInput)
Basically, for every iteration in which the while loop condition evaluates to True, it will run the code inside of the while loop. So when the user enters "" (nothing) we want the while loop condition to evaluate to False for the next iteration -- so you can implement this a variety of ways, my approach was to set a variable called functional to False.
You're right! Wrap your function in a while loop and it will keep asking until it gets something none empty!
b = ''
while b == '':
b = input("enter something")
run_my_func(b)
This works in python3
A good Pythonic while loop would look like this:
b = input("enter something")
while not b:
b = input("enter something")
run_my_func(b)

Python, not following if statements [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)
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":

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.

Categories