【问题标题】:Creating the multiplication table创建乘法表
【发布时间】:2021-07-01 14:26:12
【问题描述】:

我正在尝试创建一个乘法表。用户输入他们的数字列表,程序会输出每个数字的乘法。例如,

3 x 1 = 3
3 x 2= 6 
3 x 3 = 9
......
.....
3 x 12=42 

这是我迄今为止尝试过的:

enter code here
N = int(input("How many numbers would you like to multiply?:"))
num = []
q=1
p = 1
count=0



for i in range(0,N):
 add = int(input(f"number {i}:"))
 num.append(add)
 print(num)



for j in num:
     while q <= 12:
         print (j * q, end=" ")
         q+=1

#The result is 
How many numbers would you like to multiply?:3
number 0:2
number 1:6
number 2:5
[2, 6, 5]
2 4 6 8 10 12 14 16 18 20 22 24 
enter code here

如何让程序输出列表中每个数字的所有乘法?

【问题讨论】:

    标签: python multiplication


    【解决方案1】:

    将您的表格存储在字典中,并以您想要的任何方式调用。见以下代码:

    def inputmethod():
        N = int(input("How many numbers would you like to multiply?:"))
        num = []
        for i in range(0,N):
            add = int(input(f"number {i}:"))
            num.append(add)
        return num
    
    def multiplication(m,num):
        L = list(range(1,m+1))
        dict_tables = {}
        for n in num:
            dict_tables[n] = [e*n for e in L]
        return dict_tables
    
    def print_tables(dict_tables):
        for key,value in dict_tables.items():
            print(f"Table of {key} is : {value}")
    
    num = inputmethod()
    generate_tables = multiplication(12,num)
    print_tables(generate_tables)
    
    

    【讨论】:

      【解决方案2】:

      我会这样写(以及为什么):

      # More verbose variable names are nice documentation!
      num_count = int(input("How many numbers would you like to multiply?:"))
      
      numbers = []
      # Start at 1 instead of 0, because humans are used to counting from 1.
      for i in range(1, num_count + 1):
          number = int(input(f"number {i}:"))
          numbers.append(number)
      
      print(numbers)
      
      # Loop across the list of numbers you built in the previous step.
      for number in numbers:
          # `for i in range(...)` is the canonical Python way to loop over numbers.
          for i in range(1, 13):
              print(number * i, end=" ")
      
          print()
      

      或者:

      ...
         for i in range(12):
             print(number * (i + 1), end=" ")
      ...
      

      得到相同的结果,但我发现迭代我想要使用的实际数字列表要简单得多,尤其是在更复杂的公式中,您引用该变量的次数超过一次。例如,如果你在计算平方和写number * (i + 1) * (i + 1),而你是我的同事,我会朝你摇摆手指。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        相关资源
        最近更新 更多