简体   繁体   中英

Breaking While Loop for multiple inputs of list…for nested list

Hi I'm trying to get multiple inputs in the form of a list, which is nested inside a list. I'm able to get the output but not able to break out from the loop.

values = []
while True:
    val = list(input("Enter an integer, the value ends if it is 'stop': "))
    if val == 0:
        exit()
    values.append(val)
    print(values)

I even used break..after the if condition..no Joy !!

Enter an integer, the value ends if it is 'stop': 4569
[['4', '5', '6', '9']]
Enter an integer, the value ends if it is 'stop': 666655
[['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5']]
Enter an integer, the value ends if it is 'stop': 5222
[['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5'], ['5', '2', '2', '2']]
Enter an integer, the value ends if it is 'stop': 0
[['4', '5', '6', '9'], ['6', '6', '6', '6', '5', '5'], ['5', '2', '2', '2'], ['0']]

This is the type of output i'm looking for but whenever I press 0...it does not break the loop..

also using if val == list(0) and if list(val) == list(0) and many other permutations either gives me an error or does not break out from the While Loop...Please Help..Thank you

The returned value of input is an instance of str . So in any case you would need to use the condition val == '0' in your if-statement. But since you are creating a list from the returned value of input you would need to change your code to the following:

values = []
while True:
    val = list(input("Enter an integer, the value ends if it is 'stop': "))
    if val == ['0']:
        exit()
    values.append(val)
    print(values)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM