未定义名称"prompt"



我的代码需要向用户询问3个数字。如果数字在100以上或1以下,告诉他们"no way, try a different number"我的问题是:我不知道如何定义我的变量prompt,当我运行我的代码时,我得到下面的stacktrace

代码:

def get_int(prompt, minval, maxval):
    """gets a value for an input. if its too small or large gives error"""
    n= int(input("Choose a number between 1 and 100: "))
    maxval= n > 100
    minval= n< 1
    prompt = n
    int_choice.append(n)
    return None

int_choice=[]# list for adding inputs
for i in range (3):
    get_int(prompt, minval, maxval)
    if n== minval or n== maxval:
        print("no way, try a diffrent number")
    int_choice.append(n)
    print("you chose: ", int_choice) 
异常堆栈

:

>line 18, in <module>  
get_int(prompt, minval, maxval)  
NameError: name 'prompt' is not defined
 is the error message

我是这样处理get_int函数的:

def get_int(prompt, minval, maxval):
    '''Prompt for integer value between minval and maxval, inclusive.
    Repeat until user provides a valid integer in range.
    '''
    while 1:
        n = int(input(prompt))
        if (n < minval):
            print("value too small")
            print("value must be at least {0}".format(minval))
        elif (n > maxval):
            print("value too large")
            print("value must be not more than {0}".format(maxval))
        else:
            print("value accepted")
            return n
    pass
    # TODO: raise a ValueError or a RuntimeError exception 
    # if user does not provide valid input within a preset number tries
if __name__ == "__main__":
    # Example: test the get_int function
    # Requires user interaction.
    # Expect out-of-range values 0, 101, -5, etc. should be rejected.
    # Expect range limit values 1 and 100 shoudl be accepted.
    # Expect in-range values like 50 or 75 should be accepted.
    minval = 1
    maxval = 100
    test1 = get_int("Choose a number between {0} and {1}: ".format(
        minval,maxval), minval, maxval)
    print("get_int returned {0}".format(test1))

在函数get_int中,promptminvalmaxval参数已经定义,因为它们在参数列表中。prompt参数被传递给input()函数,然后minvalmaxval限制用于在无限while循环中进行范围检查。该函数返回一个范围内的有效数字。如果用户输入一个超出范围的整数,我们会再次询问他们,直到他们给出一个可接受的输入。因此,调用者可以保证得到指定范围内的整数。

这不是理想的设计,因为如果用户不想输入数字,但他们想"导航回来"……所以这超出了这个方法的范围。但是有一种更高级的编程技术叫做异常处理(参见try/catch/throw的例子)7.4。try语句

在函数外部,get_int被调用,minvalmaxval被定义为主模块命名空间中的全局变量。对于测试,我只是在交互模式下运行,接受单个值。在python 2.7和python 3.2上测试。

如果您以前从未见过"xxxxx {0} xxxx".format(value)字符串格式化表达式,请参阅python帮助文件第6.1.2节。字符串格式化和6.1.3.2。格式的例子。

最新更新