如何让Python将浮点数作为范围的一部分?

时间:2017-09-01 22:09:12

标签: python python-3.x range

我编写的代码给了我一个错误:它不会将浮动作为范围的一部分。

grade = float(input('How much was your annual average ?') )

if grade in range (65,100) :
     print ('Congratulations, you are promoted to the 2nd Secondary !')

elif grade in range ( 60, 64):
    print('You are promoted on the condition you pass a make-up exam.')

elif grade >100:
    print( 'Error, recheck value') 

else :
    print ('You have failed the academic year')

3 个答案:

答案 0 :(得分:0)

您在这里不需要range,您可以使用链式比较来检查浮动是否在所需的范围内

if 65 <= grade < 100: # or <= 100
     print ('Congratulations, you are promoted to the 2nd Secondary !')   
elif 60 <= grade < 64: # or <= 64
     print('You are promoted on the condition you pass a make-up exam.')
...

答案 1 :(得分:0)

range是生成的整数序列;它的不是区间描述。例如,你的&#34; D&#34; range是四个整数的列表:

>>> range(60, 64)
[60, 61, 62, 63]

我认为你想要的表达更像是

if 60.5 < grade < 64.5:

您可能想要参数化。

答案 2 :(得分:-1)

def annual(n):
    if n in range(65,101):
        print("Congratulations, you are promoted to the 2nd Secondary !")
    if n in range(60,65):
        print("You are promoted on the condition you pass a make-up exam")
    if n>100:
        print("Error, recheck value")
    if n in range(0,60):
        print("You have failed")

这是怎么回事?

def annual(n):
if 65<=n<=100:
    print("Congratulations, you are promoted to the 2nd Secondary !")
if 60<=n<=64:
    print("You are promoted on the condition you pass a make-up exam")
if n>100:
    print("Error, recheck value")
if 0<=n<=60:
    print("You have failed")