python-3.x - 其他函数如何访问在 get_goal 函数中生成的“目标”值?
问题描述
试图使“目标”值可访问其他函数,如“display_instructions”和“gameLoop”。
但是当我运行程序时,它说“目标”没有在其他函数中定义
我已经尝试将目标 = get_goal() 添加到 display_instruction() 并且它似乎有效
但确实可以尝试对 gameLoop 做同样的事情
因为它给了我一个 int()< function() 的错误
import random
def main():
goal = get_goal()
display_instruction(goal)
userInput()
gameLoop(goal)
playAgain()
def get_goal():
goal = random.randint(1, 99)
return goal
def userInput():
inputNum = input('Enter a valid coin value: ')
return inputNum
def display_instruction(goal):
instruction = ['Game Session Starts'
'Enter coins values as 1-penny, 5-nickel, 10-dime, and 25-quarter.',
'Enter coins that add up to ' + str(goal) + ' cents, one per line.']
for lines in instruction:
print(lines)
def gameLoop(goal):
totalInput = 0
while totalInput < goal:
try:
inputNum = userInput()
if inputNum == "":
print("Session Ends!")
ValueError
elif int(inputNum) in [1, 5, 10, 25]:
totalInput += int(inputNum)
else:
print("Invalid entry - Try again!")
continue
except ValueError:
print("Invalid entry - Try again!")
continue
print("Game Session Ends")
print("Here is the outcome : ")
if goal == totalInput:
print("Success!")
elif totalInput < goal:
diff = goal - totalInput
print("Failure - you only entered "+str(totalInput)+" cents")
print("You are short of "+str(diff)+" cents")
else:
diff = totalInput - goal
print("Failure - you entered "+str(totalInput)+" cents")
print("The amount exceeds "+str(goal)+" cents by "+str(diff)+" cents")
def playAgain():
secondRun = input("Play another game session (y/n)?")
if secondRun == 'y' or secondRun == 'Y':
main()
else:
print("thanks for playing... Good Bye!")
main()
我试图让它像游戏一样运行。通过添加输入值来匹配随机生成的数字“目标”
解决方案
看来我已经通过将以下代码添加到gameLoop来解决这个问题:
goal = get_goal()
goalstr = str(goal)
并将 while totalInput < 目标更改为 totalInput < int(goal)
bth,它看起来很愚蠢。
推荐阅读
- blazor - 如何在 Microsoft Blazor 应用中使用 Google Cast API?
- javascript - 在 Raspberry pi2 上启动 Electron 时出错
- r - R/dplyr 获取运行最大值
- visual-studio - VS创建的Nuget包不更新版本
- java - 在 Docker 容器(OS-Mac M1)中安装 Keyclock 时出现错误
- php - 必需的属性在codeigniter php中不起作用
- flutter - 颤振错误:(动态)=> Null 不是(字符串,动态)的子类型
- java - gradle 项目(由 IntelliJ IDEA 2021 导入)无法从 webapp 文件夹中识别 jar
- bash - 使用 bash 删除 CSF“请勿删除”IP 条目
- javascript - 从 iOS 应用程序调用函数时,Firebase HTTP 云函数给出 401 错误