سؤال

I was looking at a post by Don Marco that involved making Pascal's Triangle in python. I wanted to understand the code better so I tried played with it and tried to have it take a user input. This is the code I used:

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)

It didn't ask for any user input and I got this error:

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.

please keep in mind I'm fairly new too python. Thanks in advance.

هل كانت مفيدة؟

المحلول

You're passing the wrong parameter to range(). Try this in the outermost for loop:

range(row_ans)

Also notice that the rows parameter is not being used, delete it from the function declaration and simply call the function like this:

triangle()
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top