【问题标题】:Simple function asking for positive integer and verifying input要求正整数并验证输入的简单函数
【发布时间】:2017-04-07 18:22:22
【问题描述】:

我只是想创建一个要求正整数的函数,然后验证输入确实是正整数:

def int_input(x):
    x = input('Please enter a positive integer:')
    if x != type(int()) and x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

int_input(x)

它给了我“NameError: name 'x' is not defined”。

这太简单了,我觉得我应该在这方面找到很多帖子,所以也许我是盲人......

谢谢!

【问题讨论】:

  • 您使用的是哪个 Python 版本?
  • 不清楚为什么您的函数首先将x 作为参数,但您的最后一行肯定传递了一个未定义的x 变量。
  • @MoinuddinQuadri 3.5

标签: python function input integer


【解决方案1】:
def int_input():
    x = input('Please enter a positive integer:')
    if x != type(int()) and x < 1:
        print("This is not a positive integer, try again:")
    else:
        print(x)

int_input()

应该是这样的,你不能在不声明x的情况下调用函数int_input()

【讨论】:

    【解决方案2】:

    你定义了函数,然后通过x作为参数调用它,但是x确实没有定义在int_input(x)的范围内(在这种情况下是全局的)。

    一些更正确的代码版本是:

    def int_input(x):
        if x != type(int()) and x < 1:
            print("This is not a positive integer, try again:")
        else:
            print(x)
    
    x = input('Please enter a positive integer:')
    int_input(x)
    

    此外,这个比较:

    x != type(int())
    

    永远是False,因为type(int())永远是int(一个类型),而x是一个值。哦,你也应该将值传递给int(),否则它总是返回0

    【讨论】:

    • 我只是不明白为什么我不能将 x = input(...) 部分包含到函数中,所以我只需要调用函数来询问用户输入?至于第二部分,我确实感觉它会给我带来问题
    • 可以,但在这种情况下,您不需要将任何参数传递给您的函数。因此,您可以将其定义更改为 def int_input(): 并通过执行 int_input() 而不是 int_input(x) 来调用它
    【解决方案3】:

    我相信您的意思是让代码拒绝浮点值和负值?在这种情况下,您需要在 if 语句中使用 or 而不是 and

    def int_input(x):
        if x != type(int()) or x < 1:
            print("This is not a positive integer, try again:")
        else:
            print(x)
    
    x = input('Please enter a positive integer:')
    int_input(x)
    

    另外,我不确定您使用的是哪个版本的 python。 3.x 应该可以正常工作,但如果您使用的是 2.x,如果用户输入字符串,则会出现错误。为了防止这种情况,您可以添加一个像这样的例外:

    def int_input(x):
        if x != type(int()) or x < 1:
            print("This is not a positive integer, try again:")
        else:
            print(x)
    
    try:
        x = input('Please enter a positive integer:')
        int_input(x)
    except:
        print("This is not a positive integer, try again:")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 2015-06-21
      • 2013-05-31
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      相关资源
      最近更新 更多