是否可以表达使用Python简洁绘制的基于控制台的USA Flag?

是否可以改善以下用python 2.7编写的代码?


首先,请原谅我画错美国国旗的情况。这是我第一次进行python编程。我已经尽力了。


顺便说一句,我画了5行带空间的星星,并在这些星和4行带空间少的星星之后画了两个额外的空间。


然后,我绘制了其余的条纹。


import sys


first_time = True

second_time = False

first_stars = 6

second_stars = 5

total_lines = 11

stars1_col = 6

stars2_col = 5

total_tokens_per_line = 37

first_total_lines = 24


i = 0

for 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


此代码的输出是:

http://img3.mukewang.com/607e3cac0001b37504810329.jpg

郎朗坤
浏览 158回答 1
1回答

慕森卡

您还可以将列表理解与字符串连接一起使用。print('\n'.join([''.join(['* '[(i + l) & 1] for i in range(11)]) + '  ' + '_' * 24 for l in range(9)] + ['_' * 37] * 3))输出:* * * * * *  ________________________ * * * * *   ________________________* * * * * *  ________________________ * * * * *   ________________________* * * * * *  ________________________ * * * * *   ________________________* * * * * *  ________________________ * * * * *   ________________________* * * * * *  _______________________________________________________________________________________________________________________________________
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python