我的python程序说答案是不正确的?

时间:2018-12-28 21:51:40

标签: python compare

我不知道为什么这不是正确的。我输入了正确的答案,但说不正确,这是我输入的正确答案

import random
x = 1
score = 0
num = 1
while x == 1:
    a = random.randint(10, 201)
    b = random.randint(1, 201)
    a = int(a)
    b = int(b)
    c = a / 100 * b
    print ("What is")
    print (b)
    print ("% of")
    print (a)
    num = input()
    if c is num :
        print ("Well done!")
        score = score + 1
    elif c != num :
        print ("That is not correct, the correct answer is ", c)

3 个答案:

答案 0 :(得分:4)

在python中,'=='和'is'之间有区别。

'=='检查值是否相同,而
'is'检查它们是否是完全相同的对象
另请参阅:Is there a difference between `==` and `is` in Python?

此外,input()返回一个字符串,但是您将其与数字进行比较。您必须先使用int(num)或float(num)将用户输入转换为数字

答案 1 :(得分:0)

在这种情况下使用is比较是不正确的,因为比较是基于对象的。

您应该使用==,因为您需要比较变量的实际值

所以这个

if c is num :

应该是这个

if (c == num):

答案 2 :(得分:0)

import random
x = 1
score = 0
num = 1
while x == 1:
    a = random.randint(10, 201)
    b = random.randint(1, 201)
    c = a / 100 * (b *1.0) # adding ‘* 1.0’ makes sure c is a float. 
    print ("What is %s\% of %s?" %(b, a)) # combined the prints in one line
    num = float(input()) # Change input to float
    if c == num :
        print ("Well done!")
        score = score + 1
    elif c != num :
        print ("That is not correct, the correct answer is ", c)