【问题标题】:Generating a chart (python loop)生成图表(python循环)
【发布时间】:2017-03-18 16:42:35
【问题描述】:

用户应该能够输入他们想要做的时间表图表,然后程序将生成一个布局良好的图表。它不应该允许用户输入低于 1 的数字。它应该询问他们是否想在之后制作另一个时间表图表。请注意,您应该是嵌套循环。密切注意格式。

Example input/output


What timestables do you want to do? 5

    1   2   3   4   5   
    ----------------------------------
1 * 1   2   3   4   5   
2 * 2   4   6   8   10  
3 * 3   6   9   12  15  
4 * 4   8   12  16  20  
5 * 5   10  15  20  25  

Do you want to do another timestables chart (y for yes)? y

What timestables do you want to do? -3

Not a valid number.
What timestables do you want to do? 7

    1   2   3   4   5   6   7   
    --------------------------------------------------
1 * 1   2   3   4   5   6   7   
2 * 2   4   6   8   10  12  14  
3 * 3   6   9   12  15  18  21  
4 * 4   8   12  16  20  24  28  
5 * 5   10  15  20  25  30  35  
6 * 6   12  18  24  30  36  42  
7 * 7   14  21  28  35  42  49  

Do you want to do another timestables chart (y for yes)? nooo

Hope you got smarter!

我正在尝试编写代码以使输出看起来像上面那样,但我完全不知道该怎么做。底部是我现在所拥有的,我想知道是否有人可以帮助我弄清楚如何编写这段代码。谢谢

column = int(input("What timestables do you want to do? "))
for x in range(1, column+1):
    print(x, sep="\t")

【问题讨论】:

    标签: python for-loop input charts


    【解决方案1】:

    这应该会正确生成表格的主要部分,但是如果您尝试打印带有大量数字的时间表,它会变得混乱(不知道为什么会这样:-))

    size = int(input("Please enter the size of the table: "))
    # list comprehension to make 2d list
    arr = [[i for i in range(1, size+1)] for j in range(size)]
    # this multiplies all the numbers in the 2d list so they can be printed later
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            arr[i][j] = (i+1)*(j+1)
    # print list
    for i in range(len(arr)):
        print(str("{:2.2g}".format(i+1)) + " * " + str("{:2.2g}".format(i+1)) + "  ", end="")
        for j in range(len(arr[i])):
            print(str("{:2.2g}".format(arr[i][j])) + " ", end="")
        # newline
        print()
    

    重要的部分是str("{:2.2g}".format(i+1))。它将小数格式化为 2 位,并且 g 删除零。查看Python Decimals format

    【讨论】:

      【解决方案2】:

      您可以将end= 参数传递给print 函数。通常print 会在末尾添加\n。对于您的情况,传递选项卡是一个不错的选择:

      print(x, end='\t')
      

      【讨论】:

        【解决方案3】:

        默认情况下,打印函数添加一个"\n"。您可以更改传递参数, end =""), end ="\t")。检查这个link 它可能会有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-04
          • 1970-01-01
          • 1970-01-01
          • 2020-08-07
          • 2021-06-26
          • 2014-01-24
          • 2011-10-25
          • 1970-01-01
          相关资源
          最近更新 更多