-1

I'm trying to write a code where the program keeps getting the user input in integers and adds it to an empty array. As soon as the user enters "42", the loop stops and prints all the collected values so far.

Ex:
Input:

1
2
3
78
96
42

Output:

1 2 3 78 96

Here is my code (which isn't working as expected):

num = []

while True:
  in_num = input("Enter number")
  if in_num == 42:
    for i in num:
      print (i)
    break
  else:
    num.append(in_num)
Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33
Ramkumar G
  • 17
  • 1
  • 7

3 Answers3

2

Here is one solution, which also catches errors when integers are not entered as inputs:

num = []

while True:
    try:
        in_num = int(input("Enter number"))
        if in_num == 42:
            for i in num:
                print(i)
            break
    except ValueError:
        print('Enter a valid number!')
        continue
    else:
        num.append(in_num)
jpp
  • 159,742
  • 34
  • 281
  • 339
0

I think your issue is with the if condition: Input builtin function returns a string and you are comparing it with an integer.

in_num = None    
num = []    

while True:
    in_num = input("Enter number: ")
    if in_num == "42": #or you could use int(in_num)
        for i in num:
            print(i)
        break
    else:
        num.append(in_num)
Cibgks
  • 125
  • 6
  • probably every possible answer is in the comments now. This does not add anything new. -1 – Arpit Solanki Feb 14 '18 at 12:08
  • Maybe I was answering and had to do some work in the meanwhile? – Cibgks Feb 14 '18 at 12:11
  • 1
    You should not do like this. OP clearly saying he want to add input in `integers`. he may want to do some thing with that array. in my opinion it will mislead the OP because string and integers difference is there. – Vikas Periyadath Feb 14 '18 at 12:15
  • If you wait 16 mins for answering a question then someone else will answer it. Either way the question is not good – Arpit Solanki Feb 14 '18 at 12:16
-1

The problem is, that input is giving you a string and you check in line 5 for an int. You have to replace it to if in_num == "42" or directly convert your input("Enter number") to an int using int(input("Enter number"))

cholox
  • 13
  • 1
  • 4