-6

I am trying to print the following pattern:

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

I tried the following code:

for i in range(1,6):
    for j in range(1,6):
        if j==1 or j==5 or j==i:
            print'*'
        else:
            print' '
        print

But the output is:

*







*

*

*





*


*



*



*






*

*

*







*

I am new to Python.Please help me.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
Physx32
  • 21
  • 1
  • 3
  • 1
    Welcome to Stack Overflow! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. – Martijn Pieters Jul 21 '14 at 15:04
  • Why do you think [nested-loops] is relevant to your problem? – Wooble Jul 21 '14 at 15:05
  • For what it's worth... it printed fine on my screen. – Tanner Jul 21 '14 at 15:06
  • 2
    `print "# #\n## #\n# # #\n# ##\n# #"` – tobias_k Jul 21 '14 at 15:07
  • 3
    Until this question is reopened: Add a `,` after the first two `print` statements to prevent them from printing a line break, e.g. `print'*',` – tobias_k Jul 21 '14 at 15:23

3 Answers3

1

your code works percectly, when you save every line in a variable before printing it

for i in range(1,6):
    s = ''
    for j in range(1,6):
        if j==1 or j==5 or j==i:
            s = s + '*'
        else:
            s = s + ' '
    print s

If you want to use more print commands, you should check out the post: How to print without newline or space?

Community
  • 1
  • 1
zinjaai
  • 2,345
  • 1
  • 17
  • 29
0

This code works perfectly:

n=int(raw_input('n='))
for i in range(1,n+1):
    for j in range(1,n+1):
        if j==1 or j==n or j==i:
            print'#',
        else:
            print' ',

    print
Physx32
  • 21
  • 1
  • 3
0

for i in range(5): for j in range(5): if j == i or j ==i or j==0 or j==4 : print("*",end=" ") else: print(" ",end=" ") print()