Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Validation 是否更新函数中的变量?_Validation_Variables_Python 3.x_User Input - Fatal编程技术网

Validation 是否更新函数中的变量?

Validation 是否更新函数中的变量?,validation,variables,python-3.x,user-input,Validation,Variables,Python 3.x,User Input,我正在自学Python3.x,并且正在努力解决变量范围的问题 在我的程序中,我要求用户输入,然后运行函数检查其值。如果该值正确,我将继续。否则,我希望允许用户更改他们以前的输入并使用新值重新测试。我要查找的值是字符串:“0”、“1”、“2”和“…”“8”、“9” 下面的代码是不正确的,但这是迄今为止我能想到的最好的代码。我看到的问题是,虽然我可以在函数check_input()中更改变量user_input,但我不知道如何更改变量的范围 例如,如果我运行程序并键入“abc”进行评级,我将收到“字

我正在自学Python3.x,并且正在努力解决变量范围的问题

在我的程序中,我要求用户输入,然后运行函数检查其值。如果该值正确,我将继续。否则,我希望允许用户更改他们以前的输入并使用新值重新测试。我要查找的值是字符串:“0”、“1”、“2”和“…”“8”、“9”

下面的代码是不正确的,但这是迄今为止我能想到的最好的代码。我看到的问题是,虽然我可以在函数check_input()中更改变量user_input,但我不知道如何更改变量的范围

例如,如果我运行程序并键入“abc”进行评级,我将收到“字符太多”消息,并要求重试。我现在进入“7”,一切似乎都很美好。但当我稍后调用rating_A时,我将得到“abc”,而不是期望的“7”

我尝试用全局变量技术解决这个问题。我的困难在于,我希望检查大量的输入值,每个值都有自己的变量(rating_a、rating_B……rating_Y、rating_Z)。我想有一个更优雅的方法来实现这一点

from string import digits

def check_input(user_input):

    while True:

        if len(user_input) != 1:
            print (user_input, 'has too many characters!')
            user_input = input('try again: ')
            continue

        elif user_input in digits:
            print (user_input, 'is valid!')
            user_input = int(user_input)
            return user_input
            break

        else:
            print (user_input, 'is not a valid input!')
            user_input = input('try again: ')
            continue


rating_A = input('Please enter a value for A: ')
check_input(rating_A)
print ()
rating_B = input('Please enter a value for B: ')
check_input(rating_B)

不确定我是否真的理解您,但如果它是有效的,您已经返回了用户输入,因此

rating_A = input('Please enter a value for A: ')
rating_A = check_input(rating_A)
将最终返回值指定给变量,然后设置


否则,我很抱歉不能很好地理解您的请求。

感谢您的回复,并对不够清晰表示歉意。我想弄清楚的是,是否有一种方法可以在不使用全局变量的情况下,在check_输入函数中更改等级a。函数中的任何内容都有函数的作用域。如果您需要在it之外进行访问,则需要全局范围。如果适合你的需要,你也可以考虑上课。