TypeError: unsupported operand type(s) for &: 'int' and 'float' in Python

Dung Do Tien Oct 10 2021 167

Hello you guys, I beginner in Python and I'm also studying more about Python.

I created a method help check avg poiter of a student and print out it. My function as below:

def graduate_rate(x):
    if x < 5:
        return 'Fail'
    if x >= 5 & x < 7.5:
        return 'Pass'
    if x >= 7.5 & x < 8.5:
        return 'Credit'
    else:
        return 'Destination'

result = graduate_rate(7.56)
print(result)

But I get an exception throw TypeError: unsupported operand type(s) for &: 'int' and 'float' when I run code above.

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    result = graduate_rate(7.56)
  File "main.py", line 4, in graduate_rate
    if x >= 5 & x < 7.5:
TypeError: unsupported operand type(s) for &: 'int' and 'float'

And I am using python 3.x

Anyone can explain it to me? How can I solve it?

Thanks for any suggestions.

Have 1 answer(s) found.
  • N

    Nikhil Bharadwaj Oct 10 2021

    This error throw when you check condition of avariable with two value. Python compare not same syntax with C#, Java.

    For an example, I need check age valid in range 20-40. I can do as below:

    if 20 <= age <= 40:

    So with your function, you can change like this:

    def graduate_rate(x):
        if x < 5:
            return 'Fail'
        if 5 <= x < 7.5:
            return 'Pass'
        if 7.5 <= x < 8.5:
            return 'Credit'
        else:
            return 'Destination'
    
    result = graduate_rate(7.56)
    print(result)
    

    #Output:  Credit

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close