0

I want to receive input where there is a newline in Python.

I want to input a number and I have implemented the following code, but I get the following error

Code

string = []

while True:
    input_str = int(input(">"))
    if input_str == '':
        break
    else:
        string.append(input_str)

Error

ValueError: invalid literal for int() with base 10: ''

line error

>1
>2
>3
>
Traceback (most recent call last):
  File "2750.py", line 4, in <module>
    input_str = int(input(">"))
ValueError: invalid literal for int() with base 10: ''
prgnewbies
  • 51
  • 7

2 Answers2

0

try isdigit function of string, see below example:

string = []

while True:
    input_str = input(">")
    if input_str.isdigit():
        input_str = int(input_str)
    if input_str == '':
        break
    else:
        string.append(input_str)
Amit Nanaware
  • 3,203
  • 1
  • 6
  • 19
0

I would suggest a try-except approach:

strList = []      
while True:
    try:
     strList.append(int(input('Enter the number > ')))
    except ValueError:
        print ('Invalid number. Please try again!')
        break
print(strList)

OUTPUT:

Enter the number > 1
Enter the number > 2
Enter the number > 3
Enter the number > 
Invalid number. Please try again!
[1, 2, 3]
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • I don't think this is how they want it to behave. They want a check for equality to an empty string for `break` to occur, and the rest should be in a `try`/`except` as you have. The test for equality won't throw an exception and still allows incorrect input to not break out of the loop. This will currently break out on any non-integer-like input. – roganjosh Apr 16 '19 at 10:15
  • @roganjosh my intial thoughts as well. I'd say we see if OP clarifies this and I'll make an edit. – DirtyBit Apr 16 '19 at 10:19