Python - Ask For Input Multiple Times Til A Certain Input Disables It
Solution 1:
This is the way I'd do what you want to achieve:
final_list = []
while1:
user_input = input("Input an element: ")
if user_input == "Stop":
break
final_list.append(user_input)
print(final_list)
To incorporate this into your existing code:
deflist_maker():
"""Make a list from input"""
result = []
while1:
user_input = input("Input an element: ")
if user_input == "Stop":
break
result.append(user_input)
print(result)
list_maker()
This while
loop goes on until the if
statement inside triggers. The break
inside the if
causes the loop to exit, and then does whatever is after the loop.
This is how it looks when you run the program:
Inputanelement: 100Inputanelement: 200Inputanelement: 300Inputanelement: Stop[100, 200, 300]
The method that you tried wasn't working is because you never actually added element
to the result
list. If you still wanted to use a recursive solution rather than a while
loop, just add a line of code that appends element
to the list:
deflist_maker():
"""Make a list from input"""
result = []
defmain():
element = input("Input an element: ")
if element == "Stop":
print(result)
else:
result.append(element) # Added
main()
main()
list_maker()
Solution 2:
You don't need a break, nor do you need to do this recursively. Keep it simple:
deflist_maker(result):
"""Make a list from input"""
element = input("Input an element: ")
while element != "Stop":
result.append(int(element)) # In your example you listed numbers, not strings, the int() function will turn the element into a number
element = input("Input an element: ")
result = []
list_maker(result)
print(result)
If you want the result to exist outside of the function, you need to declare it outside the function. Lists are mutable, which means the append function will actually change the result list inside the function. That way you can print it out after the list_maker has run. You might want to make it easier for the user to quit. Update the while line to this and it will exit if they don't type in a number:
while element.isdigit():
Post a Comment for "Python - Ask For Input Multiple Times Til A Certain Input Disables It"