是否可以改善以下用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
提交
取消