Creating shapes or letters using Python

萝らか妹 提交于 2019-12-08 10:11:48

问题


So I'm trying to create the letter H out of asterisks using Python, but I can't seem to figure out on how to create a vertical line to go across in order to create the letter H using the code I have written so far:

def across(n):    
    for i in range(n):
        print ('*', end=' ')
    print()

def straight(n):
    for i in range(n):
        print ('*')

def main():
    n=6
    straight ((n-3)//2)
    across(n//2)
    straight ((n-3)//2)

main()

this is the output:

*
***
*

Any ideas? Thanks for any help in advance.


回答1:


You have to print one line at a time. Once you have switched to the next line you cannot return to the previous line. So, the idea is (e.g. for height 3), on the first iteration the code should print "star star". It should change to the next line ('\n') and then print "starstarstar" since it is the middle line. And finally, on the last line "star star" again. Hope this helps.

def line(a):
    print "*",

    for j in range(a-2):
        print " ",

    print "*",

def middleLine(a):
    for j in range(a):
        print "*",

a = int(raw_input("Enter height (odd numbers only greater than 3): "))

for i in range(a):
    if i != (a / 2):
        line(a)

    else:
        middleLine(a)

    print


来源:https://stackoverflow.com/questions/22736522/creating-shapes-or-letters-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!