Caio Fontes - 1 year ago 102
Python Question

# Weird for loop in python 2.7

I have a codewars problem and i'm new to python (less than 24hrs using it).
I'm solving the diamond problem:

You need to a string that when printed, displays a diamond shape on
the screen using asterisk ("*") characters. Please see provided test
cases for exact output format.

The shape that will be returned from print method resembles a diamond,
where the number provided as input represents the number of *’s
printed on the middle line. The line above and below will be centered
and will have 2 less *’s than the middle line. This reduction by 2 *’s
for each line continues until a line with a single * is printed at the
top and bottom of the figure.

Return null if input is even number or negative (as it is not possible
to print diamond with even number or negative number).

Please see provided test case(s) for examples.

Python Note

Since print is a reserved word in Python, Python students must
implement the diamond(n) method instead, and return None for invalid
input.

My code:

``````def diamond(n):
retorno = " *\n"
if n%3 == 0:
for i in range(n,0,-2):
retorno += i * "*"
print(retorno + str(i));
#return retorno
``````

Test case:

``````expected =  " *\n"
expected += "***\n"
expected += " *\n"
test.assert_equals(diamond(3), expected)
``````

The output:

`````` *
***3
*
****1
``````

How come the first "*" from the initialization of the var is repeating like it's inside the for loop?

Ok, let me explain you what exactly is happening in your script step by step:

That is your code with the "number of line":

``````(1)def diamond(n):
(2)    retorno = " *\n"
(3)    if n%3 == 0:
(4)        for i in range(n,0,-2):
(5)            retorno += i * "*"
(6)            print(retorno + str(i))
``````
1. line 1, n = 3
2. line 2, n = 3, retorno = " *\n"
3. line 5, n = 3, i = 3, retorno = " *\n***"
4. line 6, n = 3, i = 3, retorno = " *\n***", you print " *\n***3"
5. line 5, n = 3, i = 1, retorno = " *\n****"
6. line 6, n = 3, i = 1, retorno = " *\n****", you print " *\n****1"

So finally you have print in two times:

`````` *
***3
*
****1
``````

Please also note that in Python you should not use ";" and that if you want to test if the input number is odd you should use `n%2 == 1`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download