-2

! /usr/bin/env python3

list1=[]

print("Enter the values")


while 1:
    data=input()
    if type(data) is int or type(data) is float:
        list1.append(data)
    else:
        break

What is the mistake in the above code I want to run it multiple time but it runs for single time....

Community
  • 1
  • 1
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jpp May 15 '18 at 17:57
  • 1
    Inputs will always be a string. You need to check it by converting it with int() or float() and see if successfully converts it or not. – Aroic May 15 '18 at 18:05

1 Answers1

1

All input in python is taken in as a string. You are checking if the data is int or float without actually trying to cast it to anything first. This means your if/else ALWAYS evaluates to the else.

You need to try to parse the input into the type you want.

list1 = []
print("Enter the values")

while 1:
    data=input()
    try:
        list1.append(int(data))
    except:
        try:
            list1.append(float(data))
        except:
            break

To make it even more efficient. You could actually reduce this to ONE try-catch, but I'll let you work that one out.

Rashid 'Lee' Ibrahim
  • 1,357
  • 1
  • 9
  • 21
  • please don't suggest catching all the exception, you should only catch the one you are expecting to handle. – MooingRawr May 15 '18 at 18:31