1

I want my program to say 'invalid input' if 2 digits or more are entered so is there a way i can limit my users input to a single digit in python?

This is my code:

print('List Maker')
tryagain = ""

while 'no' not in tryagain:
    list = []

    for x in range(0,10):
        number = int(input("Enter a number: "))
        list.append(number)

    print('The sum of the list is ',sum(list))
    print('The product of the list is ',sum(list) / float(len(list)))
    print('The minimum value of the list is ',min(list))
    print('The maximum vlaue of the list is ',max(list))
    print(' ')
    tryagain = input('Would you like to restart? ').lower()
    if 'no' in tryagain:
        break
print('Goodbye')
2
  • 1
    if number >9 or number <-9 Commented Sep 26, 2016 at 13:47
  • alternatively, while number <=9 and number >=-9 Commented Sep 26, 2016 at 13:48

2 Answers 2

4

Use a while loop instead of a for loop, break out when you have 10 digits, and refuse to accept any number over 9:

numbers = []
while len(numbers) < 10:
    number = int(input("Enter a number: "))
    if not 1 <= number <= 9:
        print('Only numbers between 1 and 9 are accepted, try again')
    else:
        numbers.append(number)

Note that I renamed the list used to numbers; list is a built-in type and you generally want to avoid using built-in names.

Sign up to request clarification or add additional context in comments.

4 Comments

Is input() safe in python 2? from what I've read it is similar to eval(raw_input())
@Aaron: OP appears to be using Python 3. If OP is using Python 2 then OP should use raw_input instead of input for the reason you stated.
@StevenRumbalski I see that, and I understand that input() functions as raw_input() in Python 3. But I was curious if the 2.7 version was safe from an untrusted input point of view. (not in relation to this question...)
@Aaron: in Python 2, input() is not safe, no, as it is an automatic eval(raw_input()). This isn't Python 2 however.
0

There is another option for getting only one character, based on this previous answer:

import termios
    import sys, tty
    def getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


numbers = []
while len(numbers) < 10:
    try:
        ch = int(getch())
    except:
        print 'error...'

Comments

Your Answer

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.