I tried to do the first assignment from http://www.cplusplus.com/forum/articles/12974/
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 & g <= 100:
print 'Your grade is: A'
elif g >= 80 & g < 90:
print 'Your grade is: B'
elif g >= 70 & g < 80:
print 'Your grade is: C'
elif g >= 60 & g < 70:
print 'Your grade is: D'
elif g >= 50 & g < 60:
print 'Your grade is: E'
elif g >= 0 & g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
The problem is that whenever I run this program, any number I input that is greater than 0 will get:
Your grade is: A
Any help greatly appreciated. Thanks!
4 Answers 4
Bi Rico's answer is simple and correct. To explain the situation further:
- The
&operator computes the bitwise AND of two integers. For example,5 & 3 == 1. - The precedence of
&is above the comparison operators (such as<and>=). Soa < b & c < dactually meansa < (b & c) < d. - Python allows chained comparisons. For example,
a < b == c >= dtranslates intoa < b and b == c and c >= d.
Putting these facts together, this is what happens when you run your program:
- Assume that
gis assigned an integer value between0and100, inclusive. - So the if-test
g >= 90 & g <= 100means(g >= (90 & g)) and ((90 & g) <= 100). - Bitwise AND is always smaller than or equal to both arguments (i.e.
(a & b <= a) and (a & b <= b)). - Thus
90 & g <= gis always true. Likewise,90 & g <= 100is always true, because90 <= 100. - Therefore the first if-test is always true, so the body will execute and the elif/else clauses will never execute.
Comments
The problem in your code is that you're using & when you want to use and, try this:
if g >= 90 and g <= 100:
print 'Your grade is: A'
...
1 Comment
The code you had their was spot on but syntax is very important in Python. You want to use and where you have & like this:
g = int(raw_input('Enter the grade you scored: '))
if g >= 90 and g <= 100:
print 'Your grade is: A'
elif g >= 80 and g < 90:
print 'Your grade is: B'
elif g >= 70 and g < 80:
print 'Your grade is: C'
elif g >= 60 and g < 70:
print 'Your grade is: D'
elif g >= 50 and g < 60:
print 'Your grade is: E'
elif g >= 0 and g <= 49:
print 'Your grade is: F'
else:
print 'You can only enter an integer within the range of 0-100.'
This will display what you need the correct way.
Comments
Using the correct keyword is always important as certain things can cause errors. Use and, not &.