4

I'm new to programming and currently learning Python. I would like to write a program that :

  1. request user to input a non-negative even integer.
  2. request the user to input again if not fulfil non-negative even integer.
N = input("Please enter an non-negative even integer: ") #request user to input

And the criteria checking code is:

N == int(N) #it is integer
N % 2 == 0 #it is even number
N >=0 # it is non-negative number

But how should I combine them?

glglgl
  • 89,107
  • 13
  • 149
  • 217
useR
  • 3,062
  • 10
  • 51
  • 66

5 Answers5

5
  1. since the question is tagged python-2.7, use raw_input instead of input (which is used in python-3.x).
  2. Use str.isdigit to check if a string is an positive integer, int(N) would raise ValueError if the input couldn't be converted into integer.

  3. Use a while loop to request user input if condition not fulfilled, break when you get a valid input.

e.g.,

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
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
2

You can use the 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
phihag
  • 278,196
  • 72
  • 453
  • 469
  • It should be noted that `N == int(N)` doesn't work here in Py3, because `N` is a string. – glglgl Feb 13 '14 at 10:13
  • Updated with a Python 2.x and (with a small change) 3.x-compatible version. – phihag Feb 13 '14 at 10:18
  • Hi. Indeed i m using Python3.3.3. Why my question is unlike Python3? – useR Feb 13 '14 at 10:28
  • @SteveJessop It was not obvious, but the OP mentionned that in [another question](http://stackoverflow.com/q/21748910/296974). – glglgl Feb 13 '14 at 10:32
  • @Yin: your question is unlike Python 3 because you used `N == int(N)`. As you've been told (on your previous question) that's wrong in Python 3. So people like me who hadn't seen your previous question will assume you're using Python 2 in which it does (more or less) work. – Steve Jessop Feb 13 '14 at 11:51
1

Compared to other versions presented here, I prefer to loop without using the break keyboard. You can loop until the number entered is positive AND even, with an initial value set to -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)
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
0

Just another solution:

>>> 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
>>>
James Sapam
  • 16,036
  • 12
  • 50
  • 73
  • DRY, Don't Repeat Yourself. Omit the first `return 'Wrong Number'` and replace the 2nd one with `pass`. Put `return 'Wrong Number'` at the end of the function. – glglgl Feb 13 '14 at 10:34
-2

code for fun:

  result=[ x for x in [input("Please enter a number:")] if isinstance(x,int) and x>0 and x%2 ==0]

Excuting this list comprehension ,will get you an empty list if occurs any illegal key-in like 0.1, 'abc',999.

code for best practice:

There is quite popular to take all validation expression into lambda for python, for example, like django so :

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!"

this can also be writen as

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!"

to solve the input and raw_input difference between 2.x and 3.x:

import sys
eval_input =lambda str: input(str) if sys.version_info<(3,0,0) else eval(input(str))

then just call eval_input

ray_linn
  • 1,382
  • 10
  • 14
  • Thanks for your comment. i added() for print while it output "No Positive Even Number" even i input 6. – useR Feb 14 '14 at 04:50
  • All problem are caused by 2.x to 3.x change. a). in 2.x , print supports "softspace", but 3.x does not . b) 3.x input function equal 2.x raw_input, so all you key in are string if under 3.x, this make isinstance(x,int) return false. using eval(input(...)) in 3.x can fix this issue. – ray_linn Feb 14 '14 at 05:28