如何从函数内部传递值并将其添加到函数外部,以便创建得分计数器?
嗨,所以我是新手,并且在这部分上停留了一段时间。我正在尝试编写代码,将每次掷骰子的分数相加,然后重新掷骰子,并在每次用户告诉时添加新的分数和上一个分数。我尝试将其作为循环执行,但代码仅显示相同的数字。我在做什么错了,我该如何改善?
import random
die1 = (random.randint(1, 6))
score = 0
score = die1 + score
def onroll():
print("Do you want to roll again?")
if "y" in input():
print(die1)
print(score)
onroll()
onroll()
答案 0 :(得分:0)
由于您是编码的新手,因此如果您在跳入之前遵循快速的python教程,将会发现很多乐趣。
Python是一种有趣的编程语言,相当直观,但是只有在您学习了基础知识之后,它才是直观的:)。
在线上有一些不错的教程,例如tutorialspoint。
话虽如此,我将帮助您从基本的角度理解这一点。
import random
die1 = (random.randint(1, 6))
score = 0
score = die1 + score
# A function can take several inputs such as:
# def onroll(input1, input2):
# def onroll(myInput):
# In your case you want to pass a die and a score, so lets pass that
def onroll(score, die):
print("Do you want to roll again?")
if "y" in input():
print(die)
print(score)
# This is recursion, which is an advanced topic.
# That being said if you want to `return` values we need
# to add a return here.
# and we need to re-pass our arguments
return onroll(score, die)
# Now we can return our die and score
return die, score
# Now call the method
result_die, result_score = onroll(score, die1)
# And we can print the results.
print(result_die, result_score)
答案 1 :(得分:0)
这就是我要做的:
import random
def roll():
return random.randint(1, 6)
score = 0
role_question = "Do you want to roll?"
print role_question
while "y" in raw_input():
die1 = roll()
score += die1
print "Rolled: " + str(die1)
print "Score: " + str(score)
print role_question