python3 中的加法问题

Trouble with addition in python3

我正在制作某种计算器,实际代码更大并且工作正常...但是当涉及到 + 操作时,即使我写数字,它也会打印 'only digits supported'。其他操作,如 -、*、/ 工作 good.What 的问题?

    while True:   
        start = input("What do you want to do? + - * /  ")
        if start == '+':
            x = float(input("digit 1  "))   
            y = float(input("digit 2  "))
            res = x + y
            if type(res) is not float:
                print('Only digits  supported')
                again = input('Do u want to try again? Y/N ')
                if again=='N' or again=='n':
                    break 
        elif type(res) is float:
            print('The result is ' + str(res))
            again = input('Do u want to try again? Y/N ')
            if again=='N' or again=='n':
                break    

实际上,正如我所看到的,第 12 行代码中的代码块中存在错误,它必须在下一级(多一个选项卡)

while True:   
    start = input("What do you want to do? + - * /  ")
    if start == '+':
        x = float(input("digit 1  "))   
        y = float(input("digit 2  "))
        res = x + y
        if type(res) is not float:
            print('Only digits  supported')
            again = input('Do u want to try again? Y/N ')
            if again=='N' or again=='n':
                break 
        elif type(res) is float:
           print('The result is ' + str(res))
           again = input('Do u want to try again? Y/N ')
           if again=='N' or again=='n':
               break  

我试过 运行 你的代码,我遇到的唯一问题是 'elif' 语句缺少缩进,否则它工作正常...

您在给定代码段中的缩进不正确。 Python 中的缩进很重要(也是确定代码块的方式,因为 Python 中没有括号)。您的 elif type(res) is float 块应该进一步缩进以对应于第二个 if 语句(现在,它对应于 if start == '+' 语句。进行此更正后,代码对我有用。也许您还做了其他事情不是 post 关于导致它不适合你的代码。

更正后的代码:

while True:
        start = input("What do you want to do? + - * /  ")
        if start == '+':
            x = float(input("digit 1  "))
            y = float(input("digit 2  "))
            res = x + y
            if type(res) is not float:
                print('Only digits  supported')
                again = input('Do u want to try again? Y/N ')
                if again=='N' or again=='n':
                    break
            elif type(res) is float:
                print('The result is ' + str(res))
                again = input('Do u want to try again? Y/N ')
                if again=='N' or again=='n':
                    break