I will translate the code to plain English, as explicitly as I can:
Here are the rules that take a value `inp` and compute the `string` of that `inp`:
Letting `i` take on each integer value from 0 up to but not including `inp`:
We are done. The `string` of `inp` is equal to the string '*' repeated `i` times.
Compute the `string` of `5` and display it.
Hopefully the problem is evident: we can only be done with a task once, and i
is equal to 0 at that point, so our computed value is an empty string.
When I am writing print
, it is giving me the star output but also giving me None
From the described behaviour, I assume that you mean that you tried to replace the word return
in your code with print
, giving:
def string(inp):
for i in range (inp):
print(i*"*")
print (string(5))
That produces the triangle, of course, except that
- Since
i
will be equal to 0 the first time through the loop, a blank line is printed; and since i
will be equal to 4 the last time through the loop, there is no *****
line.
- At the end,
None
is printed, as you describe. This happens because the value computed by string
is the special value None
, which is then print
ed because you asked for it to be printed (print(string(5))
).
In Python, each call to a function will return a value when it returns, whether or not you use return
and whether or not you specify a value to return
. The default is this special None
value, which is a unique object of its own type. It displays with the text None
when printed, but is different from a string with that text (in the same way that the integer 5
is different from the string "5"
).
May I know why return
or print
are not working properly?
They are working exactly as designed. return
specifies the result of calling the function, and can only happen once per function, and does not cause anything to be displayed. print
displays what it is given.
If you wish to return
multiple values from a call, then you need to work around that restriction - either by using a generator instead (as in @MadPhysicist's or @wjandrea's answers), or by using some single, structured datum that contains all those values (for example, a list, or a tuple).