def monsterchoice():
x = random.randint(0,6)
s = random.randint(0,5)
if x > 3:
s = int(s*5)
return s
else:
print('The monster misses')
monsterchoice()
It returns NoneType and I’m not sure how to fix this.
CodePudding user response:
When the randomly generated x is bigger than 3, an integer is correctly returned.
When it is smaller or equal to 3, then nothing is returned: you are just printing a message. You could return the text message instead of printing it.
def monsterchoice():
x = random.randint(0,6)
s = random.randint(0,5)
print(x, s)
if x > 3:
s = int(s*5)
return s
else:
return 'The monster misses'
CodePudding user response:
def monsterchoice():
x = random.randint(0,6)
s = random.randint(0,5)
if x > 3:
s = int(s*5)
return s
else:
print('The monster misses')
for i in range(10):
result = monsterchoice()
print(result)
print('---------------')
Running your function a couple of times gives the following results, as you can see, you're returning None
any time the monster misses.
10
---------------
10
---------------
The monster misses
None
---------------
10
---------------
10
---------------
20
---------------
15
---------------
The monster misses
None
---------------
25
---------------
The monster misses
None
---------------
If you only want to do something when the monster doesn't miss, you can take advantage of the None
results:
for i in range(10):
result = monsterchoice()
if result:
print(result)
Output:
The monster misses
25
5
15
The monster misses
10
The monster misses
The monster misses
The monster misses
The monster misses