嵌套for循环乘法表python

2024-10-01 07:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个python类的赋值,我们必须编写一个程序,该程序要求输入,并将显示一个乘法表,其中包含输入之前的所有值。它要求我们使用嵌套的for循环。在

def mathTable(column, tuple):
    for column in range(1, 13):
        for tuple in range(1, 13):
            print("%6d" % (column * tuple), end = '')
    print("")

x = int(input("Enter the value of the multiplication table: "))
column = ""
tuple = ''
print(mathTable(column, tuple))

这就是它需要的样子:


Tags: thein程序forinputdefrangecolumn
3条回答

如果您愿意使用第三方库,那么使用numpy这是很简单的:

import numpy as np

def return_table(n):
    return np.arange(1, 13) * np.arange(1, n+1)[:, None]

print(return_table(3))

# [[ 1  2  3  4  5  6  7  8  9 10 11 12]
#  [ 2  4  6  8 10 12 14 16 18 20 22 24]
#  [ 3  6  9 12 15 18 21 24 27 30 33 36]]

你在重用变量和参数名。也就是说,在创建for循环时,应该使用新的变量来循环,这样就不会覆盖参数、列和元组。我还将元组改为row以更清晰。您的循环变量可以命名为c和r,以保持简洁。在

另外,您硬编码了13作为您的表大小。您应该确保从1循环到列数,从1循环到行数。在

def mathTable(column, row):
  for r in range(1, row): #r is a temporary variable for the outer loop
    for c in range(1, column): #c is a temporary variable for the inner loop
      print("%6d" % (c * r), end = '') #note column and row don't change now, they just act as bounds for the loop
    print("")

现在,如果你调用mathTable(3,4),你会得到一个乘法表

^{pr2}$

好吧,在我的额头撞了几个小时之后,我意识到我是一个麻木的骷髅头。在

def mathTable(column, tuple):
    for c in range(1, x + 1):
        print("")
        for t in range(1, 13):
            print("%6d" % (c * t), end = '\t')
    return("\n")

x = int(input("Enter the value of the multiplication table: "))
column = ""
tuple = ''
print(mathTable(column, tuple))

所以这就是最终完美工作的结果,我用第一个for语句定义了我请求的行数,然后第二个for语句是将这两个语句相乘的次数。 第一个for语句范围内的第二个参数直接与我的输入相关联,这允许我将表的输出更改为我想要的任何大小(请不要在其中输入9位数,永远不要在其中输入sentinel值,因此您必须关闭命令行才能对其执行任何操作)

最后,为了去掉表打印后出现的“NONE”文本,您需要记住,您已经创建了一个实际上不回答任何问题的函数,所以只要说{return(”“)}就适合我的目的,因为我已经实现了我要创建的输出。在

感谢那个帮助我的人我很抱歉当时我不理解你!在

相关问题 更多 >