Python:字符串格式和调用函数

Python:字符串格式和调用函数,python,string-formatting,Python,String Formatting,因此,我在尝试将参数num1和num2传递给函数gcd时遇到了字符串格式错误。我不知道如何解决这个问题。请容忍我,因为我是Python编程新手。谢谢 #!/usr/bin/python import sys from collections import defaultdict lines = sys.stdin.read() lineArray = lines.split() listLength = len(lineArray) def gcd(a, b): c = 0

因此,我在尝试将参数num1和num2传递给函数gcd时遇到了字符串格式错误。我不知道如何解决这个问题。请容忍我,因为我是Python编程新手。谢谢

#!/usr/bin/python
import sys
from collections import defaultdict

lines = sys.stdin.read()
lineArray = lines.split()
listLength = len(lineArray)

def gcd(a, b):
    c = 0
    if a > b:
        r = a%b
        if r == 0:
            return b
        else:
            return gcd(b, r)
    if a < b:
        c = b
        b = a
        a = c
        return gcd(a, b) 

for x in range(0, listLength):
        num1 = lineArray[x]
        num2 = lineArray[x+1]
        print num1, 'and', num2
        print gcd(num1, num2)

    print 'end'
#/usr/bin/python
导入系统
从集合导入defaultdict
lines=sys.stdin.read()
lineArray=lines.split()
listLength=len(线性阵列)
def gcd(a、b):
c=0
如果a>b:
r=a%b
如果r==0:
返回b
其他:
返回gcd(b,r)
如果a
这很简单
lineArray
不是包含整数的列表,而是包含字符串的列表。 所以当你这样做的时候:

r = a%b
它尝试格式化字符串
a
,而不是计算
a%b
。 要解决此问题,请将
a
b
转换为整数:

def gcd(a, b):
    a,b = int(a),int(b)
    c = 0
    if a > b:
        r = a%b
        if r == 0:
            return b
        else:
            return gcd(b, r)
    if a < b:
        c = b
        b = a
        a = c
        return gcd(a, b)
def gcd(a,b): a、 b=整数(a),整数(b) c=0 如果a>b: r=a%b 如果r==0: 返回b 其他: 返回gcd(b,r) 如果a 此外,在
gcd
函数中,递归永远不会结束。提示:您必须检查b是否为0。
希望这有帮助

请确保您在发布的帖子中看到的缩进与脚本中的缩进相同,如果出现异常,请发布完整的堆栈跟踪(错误发生时解释器吐出的所有内容)。当前gcd(a,b)函数中没有任何行,因为c=0的缩进,如果a>b:错误,则问题是缩进。但是,即使正确缩进,递归函数(调用该函数中的同一函数)也永远不会结束。修正这个缩进,你的新问题是为什么这个函数的执行永远不会结束