如何检查输入的值?Python 3.4

1 投票
2 回答
2553 浏览
提问于 2025-04-21 04:09
def p_parameter(p):

     if p < 10 or p > 100:
        int(input("Please try again: "))
        newp = p
        return newp
    else:
        newp <10 or newp >100
        input("Good bye")
        bye()

def main():

        speed(0)
        R=100
        r=4
        p=int(input("Please enter a number between 10 and 100: "))
        p_parameter(p)
        t_iter(R,r,p)
        Xcord(R,r,p,t_iter(R,r,p))
        Ycord(R,r,p,t_iter(R,r,p))
        input("Hit enter to close porgram")
        bye()

main()

这是我写的一个程序代码,用来画涡旋图。这个程序运行得很好,但我在这里展示的是我尝试让用户输入一个10到100之间的值给p

我想做的是检查一下p是否小于10或者大于100。如果是这样的话,就给用户一个机会重新输入一个新的p值,只要这个值在允许的范围内就可以使用。如果经过第二次检查,用户还是输入了一个不正确的p值,我希望程序能够关闭。

问题是,它检查了'p'之后又要求输入p,但只接受了第一次输入的'p'值,并没有进行第二次检查,也没有把p更新为新的值。

2 个回答

0

你解决方案中的问题和修正:

它只取了 p 的第一个值,并没有给 p 赋予新的值。

  1. 你再次询问用户输入 p,但没有把这个新值赋给 newp 变量,应该像这样:

    newp = int(input("Please try again: "))
    

没有进行第二次检查。

  1. 你的 else 语句在检查 newp 的条件时,超出了 newp 变量的作用范围,而这个变量是在 if 语句内部的。你应该把对 newp 变量的检查放在 if 语句内部,像这样:

    def p_parameter(p):
        if p < 10 or p > 100:
            newp = int(input("Please try again: "))
            if newp <10 or newp >100:
    
  2. p_parameter() 函数中,当程序没有进入 if 语句时,你没有 return 语句。所以应该改成这样:

    def p_parameter(p):
        if p < 10 or p > 100:
            newp = int(input("Please try again: "))
            if newp <10 or newp >100:
                print( "Good Bye")
                bye()
            else: 
                return newp    # need return statements like this
        else:
            return p           # need return statements like this
    

对你问题的建议解决方案:

我想检查 'p' 是否小于 10 或大于 100,如果是的话,就给用户一个重新输入新值的机会,只要这个新值在允许的范围内就可以使用。

  1. 使用 while True: 无限循环,并用 break 语句在收到正确答案时退出。
  2. 使用 tryexceptelse 块来处理 ValueError

    1. 捕捉任何由于输入不是整数而导致的错误。
    2. 检测任何超出允许范围的输入。

在第二次检查后,如果用户仍然输入了错误的 'p' 值,我希望程序能够关闭。

要关闭程序,你可以选择:

  1. 让用户按 ctrl+c(这是我个人的偏好),或者
  2. 设置一个计数器,记录 while 循环应该运行多少次来检查新输入,如果达到限制就强制程序退出,使用 sys.exit(0)(注意:你需要先 import sys 才能使用;我觉得你的 bye() 就是这么做的)。

把所有内容整合在一起:

  1. 在你的 main() 函数中,去掉 input() 语句,只保留对 p_parameter() 函数的调用,像这样: p = p_parameter()

  2. 定义 p_parameter() 函数如下:

    import sys
    def p_parameter():
        exit_counter = 1    # counter to exit after 2 tries
    
        while True:
            try:
                p = int( input( "Please enter a number between 10 and 100: ") )
            except ValueError:
                print( "Not a number, Try Again" )
            else:
                if 10 < p < 100:    # this is much faster than your approach
                    break           # exit the loop
                else: 
                    print( "Value not in range")
    
                    # increment counter to exit when 2 tries are over
                    exit_counter+=1
                    if ( counter > 2 ):
                        print( "Good Bye" )
                        sys.exit(0)  # bye()
    
         return p
    
0

你可能只需要在函数里添加提示。这是进行这类验证的标准写法:

def validate():
    while True:
        # begin inf. loop
        p = input("some prompt goes here")
        if some_validation:
            break
            # end inf. loop
        # therefore if the validation fails, it reprompts
    # once you're out of the inf. loop...
    return p

这其实是一个可以做成很不错的装饰器的事情。

def validate(validation, not_valid_warning=None):
    if not hasattr(validation, '__call__'):
        raise TypeError("validation must be callable")
    def wrapper(f):
        def wrapped(*args):
            while True:
                p = f(*args)
                if validation(p):
                    break
                if not_valid_warning:
                    print(not_valid_warning)
            return p
        return wrapped
    return wrapper

@validate(lambda x: x < 10 or x > 100)
def v_input(*args):
    return __builtins__.input(*args)

# Example..........
if __name__ == "__main__":
    v_input("Enter a number less than 10 or more than 100: ")

撰写回答