[英]Better way to print a grid without using a for loop in python
I am doing exercise 3.3 from Think Python book which asks us to write a program without using for loops to print the following grids (using only the concepts introduced so far - string replication using * operator, simple functions and passing functions as arguments)我正在做 Think Python 书中的练习 3.3,它要求我们编写一个程序而不使用 for 循环来打印以下网格(仅使用目前介绍的概念 - 使用 * 运算符的字符串复制、简单函数和将函数作为参数传递)
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
def print_line(start_char, middle_char):
print(start_char, middle_char * 4, end=" ")
print(start_char, middle_char * 4, start_char)
def draw_grid():
# print("+", "- " * 4, "+", "- " * 4, "+")
print_line("+", "- ")
# print("|", " " * 4, "|", " " * 4, "|")
print_line("|", " ")
print_line("|", " ")
print_line("|", " ")
print_line("|", " ")
print_line("+", "- ")
print_line("|", " ")
print_line("|", " ")
print_line("|", " ")
print_line("|", " ")
print_line("+", "- ")
if __name__ == "__main__":
draw_grid()
Here are questions I have:以下是我的问题:
Is there a better way of doing this in python.在python中有没有更好的方法来做到这一点。 I am new to python and would like to use this simple program to deepen python constructs我是 python 新手,想用这个简单的程序来深化 python 结构
In print_line function, I wanted to repeat the printing of "+ - - - -" twice.在print_line函数中,我想重复打印“+ - - - -”两次。 Hence, I wanted to see whether I can replicate the combined string.因此,我想看看是否可以复制组合字符串。 But when I used brackets around like print((start_char, middle_char * 4)*2)
, it ended up printing brackets.但是当我使用像print((start_char, middle_char * 4)*2)
这样的括号时,它最终打印了括号。 Is there a way to achieve this有没有办法实现这一目标
print((start_char, middle_char * 4)*2)
This creates a tuple containing two elements.这将创建一个包含两个元素的元组。
I think what you may have meant to do was this;我想你可能想做的是这个;
print((start_char + middle_char * 4)*2)
# ^ This concats the strings, instead of making a tuple.
I think that should be enough to get you back onto the right path.我认为这应该足以让你回到正确的道路上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.