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)
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
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. I am new to python and would like to use this simple program to deepen python constructs
In print_line function, I wanted to repeat the printing of "+ - - - -" twice. 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.