1

I'm looking to create code which requires an integer greater than 2 to be input by a user before continuing. I'm using python 3.3. Here's what I have so far:

def is_integer(x):
 try:
 int(x)
 return False
 except ValueError:
 print('Please enter an integer above 2')
 return True
maximum_number_input = input("Maximum Number: ")
while is_integer(maximum_number_input):
 maximum_number_input = input("Maximum Number: ")
 print('You have successfully entered a valid number')

What I'm not sure about is how best to put in the condition that the integer must be greater than 2. I've only just started learning python but want to get into good habits.

Jon Clements
143k34 gold badges254 silver badges288 bronze badges
asked Oct 3, 2013 at 10:56
1
  • int(x) can succeed for both integer and non-integer values. Even so, your function should really be called is_not_integer as defined. Commented Oct 3, 2013 at 11:36

7 Answers 7

5

This should do the job:

def valid_user_input(x):
 try:
 return int(x) > 2
 except ValueError:
 return False
maximum_number_input = input("Maximum Number: ")
while valid_user_input(maximum_number_input):
 maximum_number_input = input("Maximum Number: ")
 print("You have successfully entered a valid number")

Or even shorter:

def valid_user_input():
 try:
 return int(input("Maximum Number: ")) > 2
 except ValueError:
 return False
while valid_user_input():
 print('You have successfully entered a valid number')
SpoonMeiser
20.6k8 gold badges56 silver badges72 bronze badges
answered Oct 3, 2013 at 11:17
Sign up to request clarification or add additional context in comments.

4 Comments

x is not necessarily an integer if int(x) does not raise an error.
True, if the function always takes a string. Time to make some edits to undownvote...
@chepner It is, as long as we are using Python 3 :)
Yeah, I was just just looking at the validation function out-of-context, thinking that it could take any value, not just the string the user typed.
1

My take:

from itertools import dropwhile
from numbers import Integral
from functools import partial
from ast import literal_eval
def value_if_type(obj, of_type=(Integral,)):
 try:
 value = literal_eval(obj)
 if isinstance(value, of_type):
 return value
 except ValueError:
 return None
inputs = map(partial(value_if_type), iter(lambda: input('Input int > 2'), object()))
gt2 = next(dropwhile(lambda L: L <= 2, inputs))
answered Oct 3, 2013 at 12:12

Comments

1
def take_user_in():
 try:
 return int(raw_input("Enter a value greater than 2 -> ")) # Taking user input and converting to string
 except ValueError as e: # Catching the exception, that possibly, a inconvertible string could be given
 print "Please enter a number as" + str(e) + " as a number"
 return None
if __name__ == '__main__': # Somethign akin to having a main function in Python
 # Structure like a do-whole loop
 # func()
 # while()
 # func()
 var = take_user_in() # Taking user data
 while not isinstance(var, int) or var < 2: # Making sure that data is an int and more than 2
 var = take_user_in() # Taking user input again for invalid input
 print "Thank you" # Success
answered Oct 3, 2013 at 11:05

Comments

0
def check_value(some_value):
 try:
 y = int(some_value)
 except ValueError:
 return False
 return y > 2 
chepner
538k77 gold badges595 silver badges747 bronze badges
answered Oct 3, 2013 at 11:18

Comments

0

Hope this helps

import str
def validate(s): 
 return str.isdigit(s) and int(s) > 2
  • str.isdidig() will eliminate all strings containing non-integers, floats ('.') and negatives ('-') (which are less than 2)
  • int(user_input) confirms that it's an integer greater than 2
  • returns True if both are True
answered Nov 13, 2015 at 0:01

Comments

0

This verifies that the input is an integer, but does reject values that look like integers (like 3.0):

def is_valid(x):
 return isinstance(x,int) and x > 2
x = 0
while not is_valid(x):
 # In Python 2.x, use raw_input() instead of input()
 x = input("Please enter an integer greater than 2: ")
 try:
 x = int(x)
 except ValueError:
 continue
answered Oct 3, 2013 at 11:41

Comments

0

The problem with using the int() built-in shown in other answers is that it will convert float and booleans to integers, so it's not really a check that your argument was an integer.

It's tempting to use the built-in isinstance(value, int) method on its own, but unfortunately, it will return True if passed a boolean. So here's my short and sweet Python 3.7 solution if you want strict type checking:

def is_integer(value):
 if isinstance(value, bool):
 return False
 else:
 return isinstance(value, int)

Results:

is_integer(True) --> False
is_integer(False) --> False
is_integer(0.0) --> False
is_integer(0) --> True
is_integer((12)) --> True
is_integer((12,)) --> False
is_integer([0]) --> False

etc...

answered May 18, 2020 at 21:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.