How to create patterns in Python using nested loops?

风格不统一 提交于 2019-12-08 06:54:53

问题


I am trying to create this pattern in Python:

##
# #
#  #
#   #
#    #
#     #

I have to use a nested loop, and this is my program so far:

steps=6
for r in range(steps):
    for c in range(r):
        print(' ', end='')
    print('#')

The problem is the first column doesn't show up, so this is what is displayed when I run it:

#
 #
  #
   #
    #
     #

This is the modified program:

steps=6
for r in range(steps):
    print('#')
    for c in range(r):
        print(' ', end='')
    print('#')

but the result is:

#
  #
#
   #
#
    #
#
     #
#
      #
#
       #

How do I get them on the same row?


回答1:


Replace this...:

steps=6
for r in range(steps):
    for c in range(r):
        print(' ', end='')
    print('#')

With this:

steps=6
for r in range(steps):
    print('#', end='')
    for c in range(r):
        print(' ', end='')
    print('#')

Which outputs:

##
# #
#  #
#   #
#    #
#     #

It's just a simple mistake in the program logic.

However, it is still better to do this:

steps=6
for r in range(steps):
    print('#' + (' ' * r) + '#')

To avoid complications like this happening when using nested for loops, you can just use operators on the strings.




回答2:


Try this simpler method:

steps=6
for r in range(steps):
    print '#' + ' ' * r + '#'



回答3:


You forgot the second print "#". Put it before the inner loop.




回答4:


Try something like this:

rows=int(input("Number")) s=rows//2 for r in range(rows): print("#",end="") print() for r in range(rows): while s>=0: print("#"+" "*(s)+"#") s=s-1 print("#")



来源:https://stackoverflow.com/questions/22287100/how-to-create-patterns-in-python-using-nested-loops

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