首页 > 解决方案 > 其他函数如何访问在 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()

我试图让它像游戏一样运行。通过添加输入值来匹配随机生成的数字“目标”

标签: python-3.x

解决方案


看来我已经通过将以下代码添加到gameLoop来解决这个问题:

goal = get_goal()
goalstr = str(goal)

并将 while totalInput < 目标更改为 totalInput < int(goal)

bth,它看起来很愚蠢。


推荐阅读