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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Zaqhary
  • 11
  • 2

2 Answers2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Is `input()` safe in python 2? from what I've read it is similar to `eval(raw_input())` – Aaron Sep 26 '16 at 13:59
  • @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. – Steven Rumbalski Sep 26 '16 at 14:01
  • @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 Sep 26 '16 at 14:03
  • 1
    @Aaron: in Python 2, `input()` is not safe, no, as it is an automatic `eval(raw_input())`. This isn't Python 2 however. – Martijn Pieters Sep 26 '16 at 14:04
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...'
Community
  • 1
  • 1
Gal Dreiman
  • 3,969
  • 2
  • 21
  • 40