Home > database >  Python: store userinput in list until quit
Python: store userinput in list until quit

Time:04-26

This is my current code:

    account_number = [" "]
uinput = int(input("Type some Bank account numbers. Type "quit" to stop: "))
while uinput != "quit":
    account_number.append(uinput)
else:
    print(Kontonummern, frozenset)

I want to store "uinput" in my list "account_number" until the user enters "quit". After that the list should turn into a frozenset and print it out.

As of now I can only type 1 account number and then the programm crashes.

CodePudding user response:

That doesn't work because you don't call any more input in the loop. This means that after the first input you call up an endless loop.

Also, the termination with "quit" won't work either because you are trying to load your uinput into an integer. This means that as soon as the user enters "quit", an error occurs because this string cannot be converted into an integer value.

If you want to work only with strings, it would work like this for now:

account_number = [" "]
uinput = input("Type some Bank account numbers. Type quit to stop: ")
while uinput != "quit":
    account_number.append(uinput)
    uinput = input("Type some Bank account numbers. Type quit to stop: ")
else:
    print(account_number, frozenset)

CodePudding user response:

Try this:

account_number = [" "]
uinput = input("Type some Bank account numbers. Type quit to stop: ")
while uinput != "quit":
    account_number.append(int(uinput))
    uinput = input("Type some Bank account numbers. Type quit to stop: ")
else:
    print(Kontonummern, frozenset(account_number))

The problem was that you were never updating your uinput. And your input can be "quit" but you cast it to an int, which was also causing problems.

CodePudding user response:

You never change uinput in your loop, so once your program enters the loop, it never leaves (well, until Python runs out of memory).

The simplest way is to restructure your loop so the input call is insidie it. A separate if statement is used to test the input and break out of the loop.

account_number = []
while True:
   uinput = int(input("Type some Bank account numbers. Type "quit" to stop: "))
   if uinput == "quit":
       break
   account_number.append(uinput)
account_number = frozenset(account_number)
print(account_number)

You can also use two input() statements as shown by Jhanzaib. This strategy (which I learned to call a "priming read") but the difficulty is that you will need to change the prompt in two places if you need to change it. Of course, you can exploit this to offer two different prompts ("enter the first account number", "enter an additional account number").

  • Related