嵌套循环乘法表python

嵌套循环乘法表python,python,multiplication,Python,Multiplication,有一个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("En

有一个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))
这就是它需要的样子:


如果您愿意使用第三方库,这对于
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循环时,应该使用新变量进行循环,这样就不会覆盖参数、列和元组。我还将tuple更改为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),你会得到一个

1 2 3 4
2 4 6 8
3 6 9 12

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

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(“”)}就符合我的目的,因为我已经实现了我要创建的输出


感谢那个试图帮助我的人我很抱歉当时我听不懂你的话

好的。你有问题吗?对不起,我想知道如何使输出依赖于输入,现在代码执行,并给我一个恒定的数字墙是相同的(所有的乘法表1-12)。我是一个非常新的编程,不知道我现在做错了什么。感谢您的时间您还应该提到将
input
中的值传递到函数中并修复循环边界。对不起,我不太明白您的意思?