【问题标题】:Using a variable in a try function in another function without global (python)在没有全局(python)的另一个函数中使用try函数中的变量
【发布时间】:2020-08-05 19:17:13
【问题描述】:

如何在 main 函数的guessfunction() 中使用变量“guess”(对于范围(1,6)中的i?我收到未定义guess 的错误。最初,没有guessfunction,一切正常,但我想增加用户输入错误的可能性,这让我陷入了困境。 我在 stackexchange 上看到在函数中使用 global 是不好的做法,但即使使用 global 我也不知道如何解决我的问题。 如果可以从函数中获取变量,是否还有一种方法可以更改 int(guess)? 谢谢!

import random, sys

print("Hello. What is your name?")
name = str(input())
print("Well, " + name + ", I am thinking of a number between 1 and 20.")
number = random.randint(1, 20)

def guessfunction():
    print("Take a guess.")
    guess = input()
    for number_attempts in range(0,3):
        try:
            return guess
        except ValueError:
            print("Please enter a number in figures not as a word")
    print("You didn't enter a number in figures after 3 tries, program ended")
    sys.exit()
    
for i in range(1,6):
    guessfunction()
    if int(guess) != number:
        if int(guess) < number:
            print("Your guess is too low")
        else:
            print("Your guess is too high")
    elif int(guess) == number:
        print("Good job, " + name + "! You guessed my number in " + str(i) + " guesses")
        sys.exit()
print("Nope. The number I was thinking of was " +str(number))

【问题讨论】:

  • 将返回的内容保存到变量中。例如guess = guessfunction()

标签: python python-3.x


【解决方案1】:

你需要在你的 for 循环中初始化它:

guess = guessfunction()

【讨论】:

    猜你喜欢
    • 2013-07-27
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    相关资源
    最近更新 更多