Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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
Python 2.7 用Python编写永久程序检查整数的有效性_Python 2.7_Python 3.x_Numbers_Integer - Fatal编程技术网

Python 2.7 用Python编写永久程序检查整数的有效性

Python 2.7 用Python编写永久程序检查整数的有效性,python-2.7,python-3.x,numbers,integer,Python 2.7,Python 3.x,Numbers,Integer,我是Python的初学者,我试图编写一个小程序,要求用户输入一个大于0的整数。函数应不断向用户询问数字,直到其有效 我尝试了下面这样的方法,但是我得到了错误的结果。你能帮我理解我的错误吗 num = input('please enter a number: ' ) n = int(num) while n < 0: num = input('please enter a number: ' ) if n >= 0: print('Valid numbe

我是Python的初学者,我试图编写一个小程序,要求用户输入一个大于0的整数。函数应不断向用户询问数字,直到其有效

我尝试了下面这样的方法,但是我得到了错误的结果。你能帮我理解我的错误吗

num = input('please enter a number: ' )
n = int(num)
while n < 0:
    num = input('please enter a number: ' )
    if n >= 0:
       print('Valid number')
    else:
       print('Invalid number') 
num=input('请输入一个数字:')
n=int(num)
当n<0时:
num=input('请输入一个数字:')
如果n>=0:
打印('有效数字')
其他:
打印('无效编号')
是否可以在没有输入功能的情况下启动代码?(喜欢以num=int()开头)


感谢您抽出时间

如果您的问题是代码没有终止,则始终写入
无效数字
,这是因为您没有更新n的值。你只分配了一次。您的问题的解决方案如下:

n = -1
while n < 0:
    n = int(input('please enter a number: '))
    if n >= 0:
        print('Valid number')
    else:
        print('Invalid number')

此循环将一直持续,直到您退出程序,例如使用
ctrl+C
while True:
就像您看到的一个永远持续的循环,因为
True
参数永远不会为false

代码背后的逻辑有错误

  • 您首先要求用户输入一个数字,如果他输入一个大于或等于0的数字,while循环将永远不会启动(在您的脚本中:
    whilen<0:
    ),我认为这很好,因为正如您所说,您程序的目标是“让用户输入一个大于0的整数”

  • 如果用户输入一个小于或等于0的数字,while循环将启动,但不会中断,因为在它内部,变量
    n
    的值永远不会改变,只有
    num
    的值才会改变

  • 这是一个合适的脚本,考虑到您希望让用户输入的数字大于0,并且您希望提供有关其输入的反馈

    n = None
    
    while n <= 0:
    
        n = int(input('please enter a number: '))
    
        if n <= 0:
            print('Invalid number')
    
        else:
            pass # the loop will break at this point
                 # because n <= 0 is False
    
    print('Valid number')
    
    n=None
    
    而n“错误的结果”是什么意思?第二次使用
    input
    时,将结果绑定到名称
    num
    。while循环检查名称
    n
    ,它不会变为
    False
    。编辑您的问题以进一步解释输入、预期输出和实际输出。感谢您的明确回答,可能重复。我的意思是,我理解我复制了输入问题(请输入一个数字)。我不想复制。如果我在开始时没有写任何东西,在while循环之前,Python会给出错误。所以我不想重复输入问题。谢谢你的帮助。我很感激。我在考虑永久运行这个程序。当我输入一个正数时,您编写的程序将中断。如果我想继续检查我的数字,即使它们是积极的呢?谢谢,阿加尼刚刚更新了我的答案。希望你是那个意思。是的,这正是我的意思。非常感谢你!
    n = None
    
    while n <= 0:
    
        n = int(input('please enter a number: '))
    
        if n <= 0:
            print('Invalid number')
    
        else:
            pass # the loop will break at this point
                 # because n <= 0 is False
    
    print('Valid number')