age = float(input('enter age '))
if age != 10 or age != '11':
print('you are not 10 or 11. ')
else:
print('you are 10 or 11')
When i run this code it always prints ('you are not 10 or 11') regardless of age ?
CodePudding user response:
There are several things not working here:
age = float(input('enter age '))
If age is an integer, you should keep is an integer and not convert it to a float. Since you're a beginner, I won't go into detail, just mention that this can lead to unexpected problems. If you want to know more, read this: Is floating point math broken?
You can fix this by doing this, which will convert your input age into an integer:
age = int(input('enter age '))
Secondly, there are two problems here:
if age != 10 or age != '11':
First, the first statement age != 10
compares age to an integer, the second statement age != '11'
compares age to a string. Keep this consistent with the type of age
.
Secondly, at least on of these statements will always evaluate as True
. If age is smaller than 10 or greater than 11, both statements will be True. If age is 10, the first statement will be False
but the second will be True
, if age is 11 it will be the other way around. If you change or
to and
, this condition will only be satisfied, if age is neither 10 nor 11.
You can also do it the other way around, where you check whether your second condition is True first, which is easier to read:
if age == 10 or age == 11:
print('you are 10 or 11')
else:
print('you are not 10 or 11. ')
CodePudding user response:
Let's say you write that you are 10 years old, the if statement will make the following comparisons:
age != 10 # This returns False
And
age != '11' # This returns True
So when we write age != 10 or age != '11'
the following condition is run:
False or True
The or
operator just needs one condition to be true to return true, so False or True
will return True
and enter the if statement.
As a side note, you should replace '11'
with 11
since you want to compare with a number, not a string.
CodePudding user response:
`age = float(input('enter age '))
if (age == 10 ) or (age == 11): print('you are 10 or 11. ') else: print('you are not 10 or 11') `