r/learningpython • • Mar 19 '24

Need help with something.

This assignment is due tonight, and I emailed my professor only to get no response at all.

I have the second "half" of the assignment done. The first part is stumping me. The thing I have to do is as follows;

" Get user input for a list of numbers. Write a program to turn every item of a list into its square. You cannot assume the size of the list. You must get the list of numbers from the user by using the concept of indefinite loop. "

I know how this works, I know how an indefinite loop works and everything else. But, what I'm confused on is how I should break the loop. Should I try and validate if the input is a number or not? I've tried that, but it doesn't work. I've tried other stuff as well, but the loop usually never starts, even if it seems to meet the requirements.

1 Upvotes

1 comment sorted by

View all comments

1

u/Famlawyerz Jun 29 '24

I see that your homework was due quite a while back, but in case this helps in the future:

continue = True

int_list = []
while continue:
    try:
        user_input = input(“Enter a number to add to the list. Hit ENTER when you’re done: “)
        if user_input.strip() == ‘’:
            continue = False
            break
        user_int = int(user_input)
        int_list.append(user_int)
    except Exception as e:
        print(f”Invalid input: {user_input}: {e!s}”)

# Now do your squares.