一种函数,它使用迭代将表从1打印到10

2024-10-01 15:30:22 发布

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

def tablesOneToTen():  # a function that will print out multiplication tables from 1-10
    x = 1
    y = 1
    while x <= 10 and y <= 12:
        f = x * y             
        print(f)
        y = y + 1
    x = x + 1

tablesOneToTen() 

我试图创建一个函数,它将从1-10的乘法表中获得值。在

除了嵌套的while循环之外,我是否应该添加ifelif语句来使代码正常工作?在


Tags: and函数fromtablesifthatdeffunction
3条回答

对于这类迭代任务,最好使用for循环,因为您已经知道了所使用的边界,而且Python还使得创建for循环特别容易。在

使用while循环,您必须使用条件语句检查是否在范围内,同时显式地递增计数器,从而更容易出错。在

既然您知道您需要xy的值的乘法表,为了熟悉循环,可以创建两个for循环:

def tablesOneToTen():  # a function that will print out multiplication tables from 1-10
    # This will iterate with values for x in the range [1-10]
    for x in range(1, 11):
        # Print the value of x for reference
        print("Table for {} * (1 - 10)".format(x))
        # iterate for values of y in a range [1-10]
        for y in range(1, 11):                
            # Print the result of the multiplication
            print(x * y, end=" ")            
        # Print a new Line.
        print()

运行此操作将为您提供所需的表:

^{pr2}$

对于while循环,逻辑是相似的,但当然只是比它需要的更详细,因为您必须初始化、计算条件和增量。在

为了证明它的丑陋,while循环看起来像这样:

def tablesOneToTen():
    # initialize x counter
    x = 1

    # first condition
    while x <= 10:
        # print reference message
        print("Table for {} * [1-10]".format(x))
        # initialize y counter
        y = 1
        # second condition
        while y <=10:
            # print values
            print(x*y, end=" ")
            # increment y
            y += 1
        # print a new line
        print(" ")
        # increment x
        x += 1

使用Python 3

for i in range(1, 10+1):
    for j in range(i, (i*10)+1):
        if (j % i == 0):
            print(j, end="\t")
    print()

或者:

^{pr2}$

输出:

1   2   3   4   5   6   7   8   9   10  
2   4   6   8   10  12  14  16  18  20  
3   6   9   12  15  18  21  24  27  30  
4   8   12  16  20  24  28  32  36  40  
5   10  15  20  25  30  35  40  45  50  
6   12  18  24  30  36  42  48  54  60  
7   14  21  28  35  42  49  56  63  70  
8   16  24  32  40  48  56  64  72  80  
9   18  27  36  45  54  63  72  81  90  
10  20  30  40  50  60  70  80  90  100

希望能帮你弄到1到10张桌子。在

a = [1,2,3,4,5,6,7,8,9,10]

for i in a:
    print(*("{:3}" .format (i*col) for col in a))
    print()

相关问题 更多 >

    热门问题