Python multiple comparison for string - python

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":

Related

When i run this code, i am am not getting any output when i punch in the available input

Here is a code to take boolean input in the form of 'H' & 'C' and print the output accordingly using if-else statement. When I run this code, I am able to enter the input but I am not getting any output after entering 'H' or 'C'. Where am I going wrong?
Error message: No error message.
Expected result: On Entering 'H' - 'Its a hot day'; On Entering 'C' - 'Its a cold day'.
H = True
C = False
print("Enter if it is a hot or cold day \n , H for Hot day, C for Cold day")
i = input('enter H or C \n')
if (i == H):
print('Its a hot day')
elif (i == C):
print('Its a cold day')
You are setting H and C as True and False. Then you are comparing the input (which should be either the string "H" or the string "C") to these boolean values. They will never be equal. Instead, check if the input is either of these strings:
H = "H"
C = "C"
print("Enter if it is a hot or cold day \n , H for Hot day, C for Cold day")
i = input('enter H or C \n')
if (i == H):
print('Its a hot day')
elif (i == C):
print('Its a cold day')

While loop breaks despite conditions being false [duplicate]

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.")

Python Function to convert temperature does not work properly [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I am new in Python and I am doing an exercise in which I am supposed to convert from Celsius to Fahrenheit and viceversa. I am trying to do it trough a function which should process the user input and convert it. I am unfortunately stuck because it just partially works and I cannot understand where the problem is. Here my code:
Temperature = int(input("Give an int as temperature"))
Unit = input("insert 'C' or 'F' as unit")
Mix_input = [(Temperature, Unit)]
def convert_f_c(x):
for t, u in x:
if u == "C" or "c":
F = round((1.8 * t) + 32)
print("Converted Temp:{}F".format(F))
elif u == "F" or "f":
C = round((t-32)/ 1.8)
print("Converted Temp:{}C".format(C))
else:
print("You typed something wrong")
convert_f_c(Mix_input)
If I enter a temperature in Celsius, it works as expected:
Give an int as temperature 60
insert 'C' or 'F' as unit c
Converted Temp:140F
But with the temperature in Fahrenheit, I get a wrong output:
Give an int as temperature 45
insert 'C' or 'F' as unit F
Converted Temp:113F
It happens also with lower case:
Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:113F
the expected output would be:
Give an int as temperature 45
insert 'C' or 'F' as unit f
Converted Temp:7.2C
Also if I enter something different, I donĀ“t get the error message: "You typed something wrong", as expected, but:
Give an int as temperature 145
insert 'C' or 'F' as unit r
Converted Temp:293F
You did:
if u == "C" or "c":
and
elif u == "F" or "f":
Due to operator priority these works actually as:
if (u == "C") or "c":
and
elif (u == "F") or "f":
as all non-empty string are truthy in python, these condition are always met. To avoid this you might do:
if u == "C" or u == "c":
or
if u in ["C", "c"]:
or
if u.lower() == "c":
(and same way with elif). in is membership, lower turn str into lowercase version.
Change if u == "C" or "c" to if u == "C" or u== "c"
just or "c" will always be truthy, which is why you get the error (same for elif u == "F" or "f")

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: 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