从用户输入创建数字三角形

时间:2012-04-11 12:39:51

标签: python

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

代码:

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 个答案:

答案 0 :(得分: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可以打印整数。

答案 1 :(得分:1)

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

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

答案 2 :(得分: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]

答案 3 :(得分: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

这是你在找什么?

相关问题