Python 3意外错误TypeError

时间:2017-07-14 17:02:50

标签: python

我是python的新手并尝试创建一个python3脚本,该脚本使用欧几里德算法来查找GCD,但我一直在收到错误。

代码:

firstnum = input("Enter the first number: ")
secondnum = input("Enter the second number: ")

if firstnum == secondnum:
    print("GCD is: {}").format(firstnum)
    quit()

if firstnum > secondnum:
    while True:
        thirdnum = firstnum % secondnum
        firstnum = secondnum
        secondnum = thirdnum
        if thirdnum == 0:
            print("GCD is: {}").format(firstnum)
            quit()
        else:
            continue

if firstnum < secondnum:
    while True:
        thirdnum = secondnum % firstnum
        secondnum = firstnum
        firstnum = thirdnum
        if thirdnum ==0:
            print("GCD is: {}").format(secondnum)
            quit()
        else:
            continue

错误:

Traceback (most recent call last): File "..\Playground\", line 21, in <module>
   thirdnum = secondnum % firstnum
TypeError: not all arguments converted during string formatting

如果有办法解决此错误,请首先说明它出现的原因和原因。我也是字符串格式的新手,所以如果你知道一种更有效的方法来打印带变量的字符串,请告诉我。

1 个答案:

答案 0 :(得分:1)

此操作实际上是尝试执行字符串格式化

thirdnum = firstnum % secondnum

如果您尝试执行模数运算,则需要转换为int

firstnum = int(input("Enter the first number: "))
secondnum = int(input("Enter the second number: "))