我是编程和学习Python的新手。我想写一个程序:
N = input("Please enter an non-negative even integer: ") #request user to input
标准检查代码是:
N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number
但我该如何组合它们?
答案 0 :(得分:3)
raw_input
代替input
(在python-3.x中使用)。使用str.isdigit
检查字符串是否为正整数,如果输入无法转换为整数,int(N)
将引发ValueError
。
如果条件未满足,请使用while loop
请求用户输入,当您获得有效输入时,请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
答案 1 :(得分:2)
您可以使用and
operator:
while True:
s = input("Please enter an non-negative even integer: ")
# Use raw_input instead of input in Python 2
try:
N = int(s)
except ValueError:
continue # Not an integer, try again
if N % 2 == 0 and N >= 0:
break # Abort the infinite loop
答案 2 :(得分:1)
与此处介绍的其他版本相比,我更喜欢在不使用break
键盘的情况下循环播放。您可以循环,直到输入的数字为正和偶数,初始值设置为-1
:
n = -1
while n < 0 or n % 2 != 0:
try:
n = int(input("Please enter an non-negative even integer: "))
except ValueError:
print("Please enter a integer value")
print("Ok, %s is even" % n)
答案 3 :(得分:0)
只是另一种解决方案:
>>> def non_neg(n):
... try:
... if n & 1 == 0 and n > 0:
... return 'Even Positive Number'
... except:
... pass
... return 'Wrong Number'
...
>>> for i in [-1,-2,2,3,4,0.5,'a']:
... print i, non_neg(i)
...
-1 Wrong Number
-2 Wrong Number
2 Even Positive Number
3 Wrong Number
4 Even Positive Number
0.5 Wrong Number
a Wrong Number
>>>
答案 4 :(得分:-2)
有趣的代码:
result=[ x for x in [input("Please enter a number:")] if isinstance(x,int) and x>0 and x%2 ==0]
执行此列表理解,如果出现任何非法键入命令,如0.1,'abc',999,将为您提供一个空列表。
最佳做法代码:
将所有验证表达式用于python的lambda非常流行,例如,像django所以:
isPositiveEvenNum=lambda x: x if isinstance(x,int) and x>0 and x%2 ==0 else None
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
这也可以写成
isPositiveEvenNum=lambda x: (isinstance(x,int) and x>0 and x%2 ==0) or False
while not isPositiveEvenNum(input("please enter a number:")):
print "None Positive Even Number!"
解决2.x和3.x之间的输入和raw_input差异:
import sys
eval_input =lambda str: input(str) if sys.version_info<(3,0,0) else eval(input(str))
然后只需调用eval_input