1

Input: 4, 4 output expected:

****
*..*
*..*
****

My output:

*
*
*
*
*
.
.
*
*
.
.
*
*
*
*
*

My code:

for i in range(1, 5):
         for j in range(1, 5):
            if i == 1 or i == 4 or j == 1 or j == 4:
                print("*")
            else:
                print(".")
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
rash
  • 11
  • 3
  • Check this out: http://stackoverflow.com/questions/11266068/python-avoid-new-line-with-print-command – Bart Friederichs Nov 18 '15 at 10:08
  • You are also not taking care of any input in your code. – DeepSpace Nov 18 '15 at 10:09
  • yeah i'm sorry. I just joined this community so i hope you pardon my error. I'll be more careful the next time. – rash Nov 18 '15 at 10:18
  • 1
    Possible duplicate of [How to print in Python without newline or space?](http://stackoverflow.com/questions/493386/how-to-print-in-python-without-newline-or-space) – MrHug Nov 18 '15 at 10:32

3 Answers3

3

For a start you could try to do this:

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

The ',' stops the print command from printing a \n.

UPDATE: Then, of course, add the line break after a completed row.

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
rocksteady
  • 2,320
  • 5
  • 24
  • 40
2

This is in a line using reduce:

import sys
reduce(lambda x,z:reduce(lambda x,y : sys.stdout.write("*") if y == 1 or y == 4 or z==1 or z==4 else sys.stdout.write("."),range(1,5),None)or sys.stdout.write("\n"),range(1,5),None)

O/P :

****
*..*
*..*
****

Else try your way with loops:

for i in range(1, 5):
     for j in range(1,5):
             if i==1 or j==1 or i==4 or j==4:
                     sys.stdout.write("*")
             else:
                     sys.stdout.write(".")
     sys.stdout.write("\n")

Same O/P

Akshay Hazari
  • 3,186
  • 4
  • 48
  • 84
  • 1
    Reduce definitely takes lesser time than for loops. So this should be better – Akshay Hazari Nov 18 '15 at 11:05
  • hey yeah it is a bit advanced for me but i looked at it through the net and i got a vague idea of how it works. Nevertheless , thanks – rash Nov 18 '15 at 17:11
1

You can store the output in a variable and only print it in the outside loop:

for i in range(1, 5):
     line = ""
     for j in range(1, 5):
        if i == 1 or i == 4 or j == 1 or j == 4:
            line = line + "*"
        else:
            line = line + "."
     print line

gives as output:

****
*..*
*..*
****
Alex
  • 21,273
  • 10
  • 61
  • 73