While loop breaks despite conditions being false [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed last year.
The code asks user to pick letter a, b, or c.
while True:
user_input1 = input("Please choose a, b , c: ")
if user_input1 == "a" or "b" or "c":
break
print("This should be printed when user types in a, b, or c.")
The problem comes in when I don't type a, b , or c the loop breaks and prints the statement anyway. If I type in number 2 for an example, the code executes the break and prints the statement which isn't suppose to cause it's not letter a, b , or c.
I tried put the input variable outside the while loop but it still happens.

while True:
user_input1 = input("Please choose a, b , c: ")
if user_input1 in [ "a" , "b" ,"c"]:
break
print("This should be printed when user types in a, b, or c.")

you are condition is wrong or 'b' is not comparing input with it , so 'b' is always true or 'c' , you need to change it to :
while True:
user_input1 = input("Please choose a, b , c: ")
print(user_input1)
if user_input1 in ["a","b","c"]:
break
print("This should be printed when user types in a, b, or c.")

Related

How to avoid the semantic error in Python? [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 3 years ago.
My homework is about Fermat's Last Theorem:
1) Write a function named check_fermat that takes four parameters—a, b, c and n—and checks to see if Fermat’s theorem holds.
2) Write a function that prompts the user to input values for a, b, c and n, converts them to
integers, and uses check_fermat to check whether they violate Fermat’s theorem.
Here is my code as follows. It works.
However, there is always a "None" following the correct answer, such as "Correct! None".
It would be appreciated if you could help me with the problem. Thank you so much.
def check_fermat(a,b,c,n):
if n > 2:
print("“Holy smokes, Fermat was wrong!")
if n == 2 and a**n + b**n == c**n:
print("Correct!")
else:
print("No, that doesn’t work")
def check_number():
a = int(input("Choose a number for a: "))
b = int(input("Choose a number for b: "))
c = int(input("Choose a number for c: "))
n = int(input("Choose a number for n: "))
print(check_fermat(a,b,c,n))
check_number()
print(check_fermat(a,b,c,n))
This line is what prints None, this is because the return value of check_fermat is None.
The solution is either:
only print in check_fermat, remove print from print(check_fermat(a,b,c,n))
OR, return a string (or some other sensible return value) from check_fermat, and leave print(check_fermat(a,b,c,n)) as it is.

While statment loop in python

I am learning python, and I am stuck in an infinite while loop in the following code.
A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.
The problem is here:
while B != "y" or B != "Y" or B != "N" or B != "n":
B is always not equal to one of those. If it's "y" it is not equal to the other three, and so on. And since you are using or to combine these conditions, the loop continues if any one is true, which, as we've seen, is always the case.
Rewrite using and:
while B != "y" and B != "Y" and B != "N" and B != "n":
Or apply DeMorgan's law (factor the not out of the expression and swap and/or):
while not (B == "y" or B == "Y" or B == "N" or B == "n"):
Or best of all, write it the Python way:
while B.lower() not in "yn":
(This also accepts an empty answer, which according to your prompt is equivalent to "N". To handle this, just convert your elif to a plain else, without a condition.)
Lets use a simplified version of your while loop.
while B != "Y" or B != "y":
# ...
There is no way that this will ever evaluate to False.
If B was set to Y then B != "Y" would be False, but B != "y" would be True.
I think, in this case, it might be cleaner to do something like
while B not in ["y", "Y", "n", "N"]:
# ...
Which will then repeat until the input is one of the characters in your list.
EDIT: Some other answers have suggested using while B not in "yYnN" or equivalents. This works here because all of your expected responses are one character. If you decide later to accept "yes" as a response, then you will have to use a list like I have shown above.
The issue is that you are doing while B != "y" or B != "Y" or B != "N" or B != "n":
With or it returns true if either of its options are true. So if B="N"
b!="N" or b!=n" is true because b still isn't "n"
You can solve this by replacing all the ors with ands to get this
while B != "y" and B != "Y" and B != "N" and B != "n":
This line
elif B == "N" or "n":
Should be
elif B == "N" or B == "n":
You should use condition, simply "n" (non empty string) means true
This is the simplest solution!
while B not in "YNyn":

Python multiple comparison for string

shift = raw_input("Enter the shift the employee works in: ")
shift = shift.upper()
print shift
while (shift != "A" or shift != "B" or shift != "C" ):
shift = raw_input("Invalid Input- Please Enter a, b or c: ")
shift = shift.upper()
I need to validate that the user is choosing "a, b or c" I also must use string.upper().
However, it keeps going into the while loop even when I input "a, A, b, B, c or, C" I have the "print shift" to make sure it's inputing correctly and it is.
When I only have "shift != "A"" and type in "a or A" it won't go into the loop. It's only when I add the "B and C" that it starts to mess up. How do I fix this?
You need to use and instead of or (because x != 1 or x != 2 is always true):
while (shift != "A" and shift != "B" and shift != "C" ):
But you can do better:
while shift not in "ABC":

Is there a way to assign multiple variables for one input box - Python

How would I assign multiple variables to one GUI input box? Something like this: q1, q2, q3 = input()
This isn't how the code would go, but this is just something I want it to be like:
a, b, c = str(input("Type in a command"))
But not like this:
abc = str(input("Type in a command"))
if abc == str("a"):
print ("a is right")
else:
print ("a is wrong")
if abc == str("b"):
print ("b is right")
else:
print ("b is wrong")
if abc == str("c"):
print ("c is right")
else:
print ("c is wrong")
If I did it this way, I'd get one of them wrong and it will tell me that one is right & 2 are wrong. (a is wrong, b is right, c is wrong)
input can only return one string, but you can process it on the fly:
a, b, c = input('Type in a command').split()
This may result in ValueError if the number of "words" in the input differs from 3, so you may want to use try-except to handle it.
try:
a, b, c = input('Type in a command').split()
except ValueError:
print('Invalid input. Please enter a, b and c')
Input returns only a single string. You can store the input and then process it as per your needs. A simple and safe way to take multiple variable input is :
s = input().split()
Here, s gives you a list of your whitespace separated inputs. This can take in any number of options.
You can then process each individually :
for i in s :
if i in ('a','b','c') :
print(i, " is right")
else :
print(i, " is wrong")
If you want to use different types, you could probably use ast.literal_eval:
a,b,c = ast.literal_eval("3,4,5")
a,b,c = ast.literal_eval("3,4.5,'foobar'")
This works because ast evalutes the string into a tuple which contains literals. It is then unpacked on the left hand side. Of course, for this to work, the elements must be separated by commas.

Python: altering raw_input?

I'm trying to create a program to create a questionaiire, ultimately giving back info the user inputs. Here's my code:
. Def questionaiire:
>>. Loop = 0
>>
>> While loop != 1:
>> Print "A: name"
>> Print "B: age"
>> Print "B: Favorite color".
>> Zen = raw_input("choose a, b, or c") #my problem line
>> If zen == "a" or "A":
>> A = raw_input("Input your name: ")
>>. Elif zen == "b" or "B":
>>. B = raw_input:("Input your age: ")
>>. Elif zen == "C" or "c":
>> C = raw_input("Input your favorite color")
>> Else:
>> Print A, B, C
>> Break
The ending bit is a little more sophisticated, but essentially thats my function. Help?
I also tried inserting return after the if and elifs, but that made the program stuck(couldnt input) so i took them out
There are a number of syntax errors in your code.
You must not capitalize def, while, print, if, elif, else, break, or any other python keyword, they must be all lower case.
You need to be consistent in the casing of your variable names. Zen and zen are two different variables!
You must put parenthesis after the name of the function, like this: def questionaiire():
The period in this line is a syntax error. Remove it.
print "B: Favorite color".
The colon following raw_input in this line is a syntax error. Remove it.
B = raw_input:("Input your age: ")
I don't know what the >>s at the start of each line is, I presume it's not part of the actual source code. If it is, remove all occurances of > at the start of a line.
This line does not do what you think it does:
if zen == "a" or "A":
It's interpreted like this:
if (zen == "a") or "A":
So it's always true, since "A" evaluates to True. Write it like this instead:
if zen.lower() == "a":
Here's a working example. I've made as few changes as possible to the code, to ease comparison.
def questionaiire():
a = b = c = ""
while True:
print "a: name"
print "b: age"
print "c: favorite color"
zen = raw_input("choose a, b, or c: ")
if zen.lower() == "a":
a = raw_input("input your name: ")
elif zen.lower() == "b":
b = raw_input("input your age: ")
elif zen.lower() == "c":
c = raw_input("input your favorite color: ")
else:
print a, b, c
break
You never used the loop variable, so I've removed it. Since you use break, there's no real need for it in this code example.
The number and variety of mistakes you've made writing this short code indicates that you would really benefit from reading through at least the first few chapters of the python tutorial before programming any more python or asking further python-related questions on this site.

Categories

Resources