是否可以改善以下用python 2.7编写的代码?首先,请原谅我画错美国国旗的情况。这是我第一次进行python编程。我已经尽力了。顺便说一句,我画了5行带空间的星星,并在这些星和4行带空间少的星星之后画了两个额外的空间。然后,我绘制了其余的条纹。import sysfirst_time = Truesecond_time = Falsefirst_stars = 6second_stars = 5total_lines = 11stars1_col = 6stars2_col = 5total_tokens_per_line = 37first_total_lines = 24i = 0for i in range(total_lines): if(first_time or second_time): # if second_time is true print space at the beginning of every # second line else just empty space if(second_time): sys.stdout.write(" ") # else no space else: sys.stdout.write("") # if first_time is true print a star and a space if(first_time): j = 0 for j in range(stars1_col): sys.stdout.write("* ") # first line is done reverse these two variables second_time = True first_time = False # if not first_time print "* " and at the end of stars # write space else: m = 0 for m in range(stars2_col): sys.stdout.write("* ") # write an extra space after every second line of stars sys.stdout.write(" ") # reverse these two variables again first_time = True second_time = False # write an extra space after every second line of stars sys.stdout.write(" ") # draw the underscore lines (the stripes besides stars) l = 0 for l in range(first_total_lines): sys.stdout.write("_") # now flush out or write stripes and stars besides stripes sys.stdout.flush() # if there are 8 lines printed print a newline print("") # if stars and stripes lines are total of 8 make these variables # false if (i == 8): first_time = False second_time = False此代码的输出是:
1 回答

慕森卡
TA贡献1806条经验 获得超8个赞
您还可以将列表理解与字符串连接一起使用。
print('\n'.join([''.join(['* '[(i + l) & 1] for i in range(11)]) + ' ' + '_' * 24 for l in range(9)] + ['_' * 37] * 3))
输出:
* * * * * * ________________________
* * * * * ________________________
* * * * * * ________________________
* * * * * ________________________
* * * * * * ________________________
* * * * * ________________________
* * * * * * ________________________
* * * * * ________________________
* * * * * * ________________________
_____________________________________
_____________________________________
_____________________________________
添加回答
举报
0/150
提交
取消