用while编写一个简单的函数

And*_*̷y̷ 8 python

Python家庭作业分配要求我写一个函数"将输入作为正整数,并打印出一个乘法,表格显示所有整数乘法,包括输入数字."(也使用while循环)

 # This is an example of the output of the function
print_multiplication_table(3)
>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 1 * 3 = 3
>>> 2 * 1 = 2
>>> 2 * 2 = 4
>>> 2 * 3 = 6
>>> 3 * 1 = 3
>>> 3 * 2 = 6
>>> 3 * 3 = 9
Run Code Online (Sandbox Code Playgroud)

我知道如何开始,但不知道接下来该做什么.我只需要一些算法帮助.请不要写正确的代码,因为我想学习.而是告诉我逻辑和推理. 这是我的推理:

  1. 该函数应将所有实数乘以给定值(n)乘以1小于n或(n-1)
  2. 该函数应将所有实数乘以n(包括n)乘以小于n或(n-2)的两倍
  3. 该函数应将所有实数乘以n(包括n)乘以小于n或(n-3)的三倍,依此类推......直到达到n
  4. 当函数达到n时,该函数还应将所有实数乘以n(包括n)乘以n
  5. 然后该函数应该停止或在while循环中"中断"
  6. 然后该函数必须打印结果

所以这就是我到目前为止所做的:

def print_multiplication_table(n): # n for a number
    if n >=0:
        while somehting:
            # The code rest of the code that I need help on

    else:
        return "The input is not a positive whole number.Try anohter input!"
Run Code Online (Sandbox Code Playgroud)

编辑:这是我所有人的精彩答案之后我所拥有的

"""
i * j = answer
i is counting from 1 to n
for each i, j is counting from 1 to n 
"""


def print_multiplication_table(n): # n for a number
    if n >=0:
        i = 0
        j = 0 
        while i <n:
            i = i + 1
            while j <i:
                j = j + 1
            answer = i * j
            print i, " * ",j,"=",answer

    else:
        return "The input is not a positive whole number.Try another input!"
Run Code Online (Sandbox Code Playgroud)

它还没有完全完成!例如:

print_multiplication_table(2)
# The output 
>>>1  *  1 = 1
>>>2  *  2 = 4
Run Code Online (Sandbox Code Playgroud)

并不是

>>> 1 * 1 = 1
>>> 1 * 2 = 2
>>> 2 * 1 = 2
>>> 2 * 2 = 4 
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

vro*_*del 4

我对循环的要求有点生气while,因为for在 Python 中循环更适合这种情况。但学习就是学习!

让我们想想。为什么要做一个While True?如果没有break语句,它永远不会终止,我认为这有点蹩脚。还有一个条件怎么样?

那么变量呢?我想你可能需要两个。每个要相乘的数字对应一个。并确保在循环中添加它们while

如果您需要更多帮助,我很乐意添加此答案。

你的逻辑很好。但这是我的总结:

当两个数的乘积为 时停止循环n * n

同时,打印每个数字及其乘积。如果第一个数字不是 n,则增加它。一旦达到 n,就开始增加第二个。(这可以使用 if 语句来完成,但嵌套循环会更好。)如果它们都是 n,则块while将中断,因为条件将得到满足。

根据您的评论,这里有一小段提示伪代码:

while something:
    while something else:
        do something fun
        j += 1
    i += 1
Run Code Online (Sandbox Code Playgroud)

i 和 j 的原始赋值应该去哪里?什么是某事、其他事和有趣的事?

  • @Andy:很好的尝试,但我认为你过于复杂化了。想想你的桌子。第一列发生了什么?第二个呢?这是否表明存在任何“遏制”关系(一物套在另一物内)?就像,也许,从 1 到 3 的循环? (2认同)