繁体   English   中英

在 python 中创建具有嵌套循环的表

[英]Creating a table with nested loops in python

我正在学习中止嵌套循环,并且我得到了一个任务来创建一个 function ,它需要两个 integer 输入。 然后它应该在这个图像中创建类似的东西。 唯一的问题是,当我对列使用奇数时,它不起作用。

要批准分配,它必须是“高级嵌套循环”。

def createTable(rows, columns):
    rows = int(input("Enter number of rows: "))
    columns = int(input("Enter number of columns: "))

    for row in range(rows):
        if row%2 == 0:              
            for col in range(0, columns):
                if col%2 == 1:
                    if col != columns - 1:
                        print(" ", end="")
                    else:
                        print(" ")
                else:
                    print("|", end="")
        else:
            print("-" * (columns - 1))
            
    return True

创建表(1, 2)

我已经对您想要的代码进行了一次迭代。 它为偶数和奇数行和列打印正确的 output。 它与您想要的输出非常相似。 当您为您的问题提供进一步说明时,我可以提供更新的代码。

rows = 20
columns = 41

for i in range(rows):
    if i%2 == 0:
        output = "| " * (columns//2)
        print(output)
    else: 
        output = "-" * ((columns//2)*2 - 1)
        print(output)    

output 如下图所示。 希望这能解决您的疑问。

在此处输入图像描述

根据问题提供者提供的代码,我已经编辑了代码,下面的代码将以与嵌套循环相同的方式工作。

def createtable(rows, columns): 
    for row in range(rows):
        if row%2 == 0:              
            for col in range(0, ((columns+1)//2)*2, 2):
                print("| ", end="")
            print()
        else:
            print("-" * (((columns+1)//2)*2 - 1))

    return True

对这两种情况都进行了测试。

createTable(20, 40)
createTable(20, 41)
createTable(2, 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM