How to Limit the User Input to Only Integers in Python

How can I limit the user input to only integers in Python

Your code would become:

def Survey():

print('1) Blue')
print('2) Red')
print('3) Yellow')

while True:
try:
question = int(input('Out of these options\(1,2,3), which is your favourite?'))
break
except:
print("That's not a valid option!")

if question == 1:
print('Nice!')
elif question == 2:
print('Cool')
elif question == 3:
print('Awesome!')
else:
print('That\'s not an option!')

The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put '1', it would break the loop. But if I put 'Fooey!' the error that WOULD have been raised gets caught by the except statement, and it loops as it hasn't been broken.

Python limit input

One of the best things about programming is that for any repetitive task on the human side, you can put the burden on the computer instead.

So, if for each pice of data you are: calling the built-in input, converting its result to integer, checking if the value is positive and non zero - the best way to go is to group these functionalities in a single function and then you just call that function - your main application then delegates the part of acquiring clean numbers, and becomes much simpler:


def int_input(prompt_message):
done = False
while not done:
value_str = input(prompt_message)
try:
value = int(value_str)
except ValueError:
print("Please, type a valid integer number!")
continue
if value < 1:
print("Please type a strictly positive number!")
continue
done = True
return value

This is a bit verbose, on purpose, so it is clear that once you create a function, you can add as many simple steps as needed to do your subtask (including writing further sub-functions to be called).

Once you have that function, your program can be rewritten as:

print("To calculate the sum of the arithmetic and geometric progression, you need to know the first element in the sequence of numbers, the differential, ratio and number of terms.")

a_1 = int_input("what is the first number in the arithmetic progression?")
d = int_input("what is the differential?")
g_1 = int_input("what is the first number in the geometrical progression?")
q = int_input("what is the ratio?")
n= int_input("what is the number of terms?")

# proceed to calculations:
...

And each variable is guaranteed to contain a proper positive integer, with the user being prompted until they type a suitable value, for each of them, at no cost of extra typing for each value.

As for your code: it looks all right, but for the fact that it only checks the value on a_1 for being strictly positive - so youp´d have to modify the if clause to check all the variables. (or add one if clause for each variable) - and still: it would collect all input first, and then check for negative numbers or zero.

Limiting user input in a list of integers in Python 3.x

You have two options:

  • Take the first five values from a line, ignore the rest
  • Check the length and tell the user to not enter so many values

The latter would give the user better feedback, where the first could lead to surprises (What happened to the numbers at the end of my line?)

Ignoring the rest is easy; slice the list you create; the [:5] creates a new list with just (up to) 5 values:

a = [int(x) for x in input().split(maxsplit=5)[:5]]

The above also tells str.split() to only split up to 5 times, to avoid further work.

An error message should, by command-line tool convention, be written to sys.stderr and you would exit with a non-zero exit code:

a = [int(x) for x in input().split()]
if len(a) > 5: # or len(a) != 5 if you must have exactly 5 values
print('No more than 5 values, please!', file=sys.stderr)
sys.exit(1)

When you use a library to handle command-line parsing, then the library usually includes a function to handle error communication and exit (such as argparse, where you'd use parser.error(message) to signal an issue and exit in one step).

How to limit input integer in single digit? [python]

just a quick fix

def get_single_digit_input():
while True:
a = input('please enter number')
if not a.isnumeric():
print('please enter single digit Numeric only')
continue
a = int(a)
# your logic is here
if a<=9 and a>=0:
return a
else:
print('please enter single digit Numeric only')

a = get_single_digit_input()


Related Topics



Leave a reply



Submit