boonie
boonie

Reputation: 13

Python: Give validation for input into list

I would like to input values into my_list. However, the values should only be integers. Also, if any other key than 'q' is entered, the input should show a message. However, if q is entered, the program should stop taking input and print the list.

In this program, the validation for q isn't working. Any other value than integer throws the same message 'Enter integer values only'. This happens even when the input is 'q'. Why does this happen? And what is the solution for this?

my_list = []

print("Enter q once done")

while True:
    try:
        my_list.append(int(input()))
    except:
        if input == 'q':
            break
        else:
            print("Give integer values only")
            continue

print(my_list)

Upvotes: 0

Views: 243

Answers (2)

Alex Sveshnikov
Alex Sveshnikov

Reputation: 4329

Minimal modification of you code gives:

my_list = []

print("Enter q once done")

while True:
    try:
        s = input()
        if s == 'q':
            break
        my_list.append(int(s))
    except:
        print("Give integer values only")

print(my_list)

This code has a problem, that it does not recognize end of input/keyboard interrupts. It might be better to read lines from stdin while there is still some input there:

import sys
my_list = []

print("Enter q once done")

for line in sys.stdin:
    if line == 'q\n':
        break
    try:
        my_list.append(int(line))
    except ValueError:
        print("Give integer values only")

print(my_list)

Upvotes: 2

Gaurav Agarwal Garg
Gaurav Agarwal Garg

Reputation: 113

  1. Recommended read for Try-Except in Python

ValueError exception must be raised for such a case, Here's a snippet:

  • Break only if q is entered
  • rest of the cases, continue
my_list = []

while True:
    try:
        x = input("Please enter a number or `q` for exit:")
        if(x == 'q'):
            break
        my_list.append(int(x))

    except ValueError:
        print("Oops! Give integer values only")

print(my_list)

Upvotes: 1

Related Questions