0

我正在尝试使用 Python 从用户输入中创建一个数字三角形。我写了一段代码,但不确定如何在 python 中做一件事。我想将 print("Next row") 相应地更改为相应的行。我怎么做?

代码:

numstr= raw_input("please enter the height:")
rows = int( )
def triangle(rows):
    for rownum in range (rows)
        PrintingList = list()
        print("Next row")
        for iteration in range (rownum):
            newValue = raw_input("Please enter the next number:")
            PrintingList.append(int(newValue))
            print() 

我的代码有错误吗?或者有什么改进的建议吗?请告诉我..谢谢...

4

4 回答 4

1

您可以将代码更改为此:

numstr= raw_input("please enter the height:")
rows = int(numstr )
def triangle(rows):
  for rownum in range (rows):
      PrintingList = list()
      print "row #%d" % rownum
      for iteration in range (rownum):
          newValue = raw_input("Please enter the number for row #%d:" % rownum)
          PrintingList.append(int(newValue))
          print()

通过使用,print "%d" % myint您可以打印一个整数。

于 2012-04-11T12:45:50.250 回答
1

我不确定您的程序所需的行为是什么,但这是我的猜测:

numstr= raw_input("please enter the height:")

rows = int(numstr) # --> convert user input to an integer
def triangle(rows):
    PrintingList = list()
    for rownum in range (1, rows + 1): # use colon after control structure to denote the beginning of block of code        
        PrintingList.append([]) # append a row
        for iteration in range (rownum):
            newValue = raw_input("Please enter the next number:")
            PrintingList[rownum - 1].append(int(newValue))
            print() 

    for item in PrintingList:
      print item
triangle(rows)

这是输出:

please enter the height:3
Please enter the next number:1
()
Please enter the next number:2
()
Please enter the next number:3
()
Please enter the next number:4
()
Please enter the next number:5
()
Please enter the next number:4
()
[1]
[2, 3]
[4, 5, 4]
于 2012-04-11T12:55:01.887 回答
1

如果我理解您的问题,请更改print("Next row")print("Row no. %i" % rownum).

阅读字符串文档,其中解释了%格式代码的工作原理。

于 2012-04-11T12:53:56.007 回答
0
n = int(input())

for i in range(n):
    out=''
    for j in range(i+1):
        out+=str(n)
    print(out)

这将打印以下内容:

>2

2
22

>5

5
55
555
5555
55555

这是你要找的吗?

于 2018-01-08T07:34:22.677 回答