So I wrote this code and it works, however, I'm trying to find a way to make this code return the right output, as shown down below. Here is my code.
upto = 5
def original_num(upto:int):
for x in range(1, upto 1):
print (x, (7**x)%97)
def powerLoop(upto: int):
upto = upto
return original_num(upto)
print(powerLoop(upto))
But when I print the output, this is what I get...
1 7
2 49
3 52
4 73
5 26
None
But if I use print instead of return in the code,
upto = 5
def powerLoop(upto:int):
for x in range(1, upto 1):
print(x, (7**x)%97)
powerLoop(upto)
This is what I get,
1 7
2 49
3 52
4 73
5 26
How can I use return and then once I say print(powerloop(upto)
the output will occur without printing 'none'?
CodePudding user response:
Your original_num(...)
function already prints the desired output and returns None
which you ultimately print in print(powerLoop(upto))
.
Just:
powerLoop(upto)
will not print the return value, but still "harvest" the side-effects of the function calls (the other print
s).
CodePudding user response:
Why you print again?
upto = 5
def original_num(upto:int):
for x in range(1, upto 1):
print (x, (7**x)%97)
def powerLoop(upto: int):
return original_num(upto)
powerLoop(upto)
above, the last line, just cancel print, because your function original_num
had already print the result.
and in python, if your function have nothing to return, it will return None, and then you print None.
def abc():
a=100
print(abc())
above example will get None.
CodePudding user response:
If you want to write print(powerLoop(upto))
and don't get None
you can use yield
like below:
>>> upto = 5
>>> def powerLoop(upto:int):
... for x in range(1, upto 1):
... yield (x, (7**x)%97)
>>> print(*powerLoop(upto), sep='\n')
(1, 7)
(2, 49)
(3, 52)
(4, 73)
(5, 26)
>>> for ret in powerLoop(upto):
... print(*ret)
1 7
2 49
3 52
4 73
5 26
If you want to use return
you can use list
and return list
like below: (Edit answer base comment)
>>> upto = 5
>>> def powerLoop(upto:int):
... out = []
... for x in range(1, upto 1):
... out.append([x, (7**x)%97])
... return out
>>> print(*powerLoop(upto), sep='\n')
[1, 7]
[2, 49]
[3, 52]
[4, 73]
[5, 26]
>>> for ret in powerLoop(upto):
... print(*ret)
1 7
2 49
3 52
4 73
5 26