我是编程新手,目前正在学习 Python。我想编写一个程序:
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)
但是我应该如何将它们结合起来?
raw_input而不是input(在 python-3.x 中使用)。使用str.isdigit检查一个字符串是一个正整数,int(N)将提高ValueError,如果输入无法转换为整数。
当您获得有效输入时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)
| 归档时间: |
|
| 查看次数: |
12625 次 |
| 最近记录: |