Search This Blog

Loading...

Monday, March 24, 2008

My First Ever Program in Python

I don't know much about Python, although I tried to learn it a few weeks ago. Today I decided to write a small program in Python. This program does nothing, but to output the following rectangular box:

A simple two-loop program should be able to do the job. Here's my code in Python (OK, all the indentations are lost):


def PrintStar(width):
for j in range(1, width+1):
if j == 1:
astr = '*'
elif j == width:
astr += '*'
else:
astr += ' '
return astr

def PrintAll(width):
astr =''
for j in range(1, width+1):
astr+="*"
return astr

width = 5
height =10
for i in range(1, height+1):
if i==1:
print PrintAll(width)
elif i==height:
print PrintAll(width)
else:
print PrintStar(width)


And here's my code in C#:

int width =5;
int height = 10;
for(int i=1; i<=height; i++)
{
for(int j=1; j<=width ; j++)
{
if(i==1||i==height||j==1||j==width)
Console.Write("*");
else
Console.Write(" ");
}
Console.Write("\n");
}


I realize that my Python code is verbose; I'm sure there is a more succinct way of doing it. But I couldn't find the equivalent C# operator of '||' and 'print'. It's my fault, really, to write such a verbose program, not Python's.

Anyone knows how to simplify the above Python program?

2 comments:

Anonymous said...

I'm also new to python, but I'll give it a go:

width = 5
height = 10
output = ""
for i in range(1, height + 1):
for j in range(1, width + 1):
if i == 1 or i == height or j == 1 or j == width:
output += "*"
else:
output += " "
output += "\n"
print output

No idea if it's correct, but it's more or less your C# version in Python. I only added 'output' because I think the print statement adds spaces and such.

Soon Hui said...

Thanks, anonymous, your version is not so much different from
my improved version