1

我正在查看 Don Marco 的一篇文章,其中涉及在 python 中制作 Pascal 的三角形。我想更好地理解代码,所以我尝试使用它并尝试让它接受用户输入。这是我使用的代码:

def triangle(rows):
    row_ans= raw_input('how many rows would you like')
    row_ans =int(row_ans)
    for rownum in range (rows):
        newValue=1
        PrintingList = [newValue]
        for iteration in range (rownum):
            newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 )
            PrintingList.append(int(newValue))
        print(PrintingList)
    print()
triangle(row_ans)

它没有要求任何用户输入,我收到了这个错误:

Traceback (most recent call last):
  File "/Users/centralcity/Desktop/Computer Science!/Pascal's triangle", line 13, in 
<module>          
    triangle(row_ans)
  File "/Users/centralcity/Desktop/Computer Science!/Pascal's triangle", line 3, in       
  triangle      
for rownum in range (rows):
    TypeError: range() integer end argument expected, got str.

请记住,我也是相当新的python。提前致谢。

4

1 回答 1

1

您将错误的参数传递给range(). for在最外面的循环中试试这个:

range(row_ans)

还要注意rows参数没有被使用,从函数声明中删除它,然后像这样简单地调用函数:

triangle()
于 2014-01-06T00:31:50.920 回答