完美的方形python程序不会返回预期的结果

时间:2016-03-13 19:20:09

标签: python

当我使用一个显然不是完美正方形的数字时,它仍然会返回说它是,我已经找了一个解决方案的年龄但是这里的代码没有运气:

try:
    while True:
        test_cases = int(input('How many test cases will you run, maximum of 30? '))#the ammount of test cases the user wants
        if test_cases >= 30: #exceeding the amount of test cases asked for in the specification
            print('Too high')
            pass
        else:
            break
except ValueError:#if the data entered isnt an integer
        print('Wrong data type')
        pass#re-run the try statement

x = 0
for x in range(test_cases):#loop runs for the amount of test cases the user wanted
    try:
        while True:
            tested_number = input('What number do you want to test, maximum is 10000? ')
            if int(tested_number) >= 10000:
                print('Number too large')
                pass
            else:
                break
    except ValueError:
        print(tested_number, 'is not an integer')

    if tested_number[-1] == ('2', '3', '7', '8'):#take the last element of the string and checks if it is equal to one of the values in the brackets
        print(tested_number, 'is not a perfect square')
        break
    y = 0   
    sum_of_number = sum(int(y) for y in tested_number)#the sum of all the number in the list, highest is 36 due to 10000 limit
    if sum_of_number > 9:
        sum_of_number = str(sum_of_number)
        digital_root = sum_of_number[0] + sum_of_number[1]
        if digital_root == (2, 3, 5, 6, 8, 9):
            print(tested_number, 'is not a perfect square')
            break
        else:
            print(tested_number, 'is a perfect square')
    elif sum_of_number == (2, 3, 5, 6, 8, 9):
        print(tested_number, 'is not a perfect square')
    else:
        print(tested_number, 'is a perfect square')

我知道有很多东西要看,但老实说我找不到解决方案而且我不知道程序在哪里开始失败。感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

你让运营商混淆测试平等:" ==" - 与运营商一起测试一个团体的成员资格"在"。

所以三行如

if foo == (1, 2, 3):

应该是

if foo in (1, 2, 3):

更改这些行应该可以使您的测试有效。