0

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)
1
  • 3
    input is a built-in function, it is not a pointer to the input entered by the user. Just store it in a variable. Commented Mar 15, 2020 at 8:00

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1
  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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.