Issue
I'm writing a program that stores 3 players and their scores in a list and then prints them out at the end. Simple stuff really, however I'm trying to call the value for the player score from a function called playerscore() which prevents you from entering a score >5.
this works fine when you run through it with the correct value, but if you input an incorrect value > 5 then it begins the playerscore function again and allows for a new value to be entered but returns "None"
teamlist = []
def playercreator():
counter=0
while counter < 3:
name = playername()
score = playerscore()
print(score) #check - this one goes wrong when returned after the if/else in playerscore()
teamlist.append(name+" "+str(score))
counter = counter + 1
def playername():
name=input("What name do you want for your player?\n")
return (name)
def playerscore():
global teamtotal
score=input("input score?\n")
print(score) #check
if int(score)>5:
print("Your attack score must be between 0 and 5")
print(score) #check
playerscore()
else:
return int(score)
playercreator()
for x in teamlist:
print(x)
for example, these are the inputs and outputs:
What name do you want for your player?
p1
input score?
3
What name do you want for your player?
p2
input score?
6
Your attack score must be between 0 and 5
input score?
5
What name do you want for your player?
p3
input score?
2
p1 3
p2 None
p3 2
I feel like there's something obvious that i'm missing. Can anyone point me in the right direction?
Solution
You are missing a return statement in the if block (when the score is greater than 5):
def playerscore():
global teamtotal
score=input("input score?\n")
if int(score)>5:
print("Your attack score must be between 0 and 5")
return playerscore()
else:
return int(score)
Output:
What name do you want for your player?
shovon
input score?
2
2
What name do you want for your player?
sorida
input score?
23
Your attack score must be between 0 and 5
input score?
43
Your attack score must be between 0 and 5
input score?
234
Your attack score must be between 0 and 5
input score?
1
1
What name do you want for your player?
shody
input score?
2
2
shovon 2
sorida 1
shody 2
From official documentation:
In fact, even functions without a return statement do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).
Answered By - arsho
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.