名称 "prompt" 未定义

Name "prompt" not defined

我的代码需要向用户询问 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 循环中的 运行ge 检查。函数 returns 运行ge 内的有效数字。如果用户输入的整数超出 运行ge,我们会再次询问他们,直到他们给出可接受的输入。所以调用者是 gua运行teed 得到一个在指定的 运行ge.

范围内的整数

这不是理想的设计,因为如果用户不想输入数字,但他们想要 "navigate back"... 那么这超出了此方法的范围。但是有一种更高级的编程技术称为异常处理(例如阅读 try / catch / throw7.4. The try statement.

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

上测试

如果您以前从未见过 "xxxxx {0} xxxx".format(value) 字符串格式化表达式,请参阅 python 帮助文件部分 6.1.2. String Formatting and 6.1.3.2. Format examples