在 Python 中检查非负偶数

use*_*seR 4 python python-3.x

我是编程新手,目前正在学习 Python。我想编写一个程序:

  1. 要求用户输入一个非负偶数。
  2. 如果不满足非负偶数,则要求用户再次输入。
N = input("Please enter an non-negative even integer: ") #request user to input
Run Code Online (Sandbox Code Playgroud)

标准检查代码是:

N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number
Run Code Online (Sandbox Code Playgroud)

但是我应该如何将它们结合起来?

zha*_*hen 5

  1. 由于问题被标记为python-2.7,请使用raw_input而不是input(在 python-3.x 中使用)。
  2. 使用str.isdigit检查一个字符串是一个正整数,int(N)将提高ValueError,如果输入无法转换为整数。

  3. 当您获得有效输入时while loop,如果条件不满足,请使用 a请求用户break输入。

例如,

while True:
    N = raw_input("Please enter an non-negative even integer: ") #request user to input
    if N.isdigit(): # accepts a string of positive integer, filter out floats, negative ints
        N = int(N)
        if N % 2 == 0: #no need to test N>=0 here
            break
print 'Your input is: ', N
Run Code Online (Sandbox Code Playgroud)

  • `N.isdigit()` 为真意味着你不需要测试 `N>=0`。 (3认同)