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(".")
4
  • Check this out: stackoverflow.com/questions/11266068/… Commented Nov 18, 2015 at 10:08
  • You are also not taking care of any input in your code. Commented Nov 18, 2015 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. Commented Nov 18, 2015 at 10:18
  • 1
    Possible duplicate of How to print in Python without newline or space? Commented Nov 18, 2015 at 10:32

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need '' in print '' in Python 2.x :) print is enough.
Thanks! it is kind of a "good style" for me personally. But maybe I change that into an even better style ;)
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

2 Comments

Reduce definitely takes lesser time than for loops. So this should be better
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
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:

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

1 Comment

Thank you , that was helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.