I’m trying to have the user input a number, that input is checked to see if it says “stop”, then the number is added to a list. I want it to keep going until you type “stop” and then display the list. I’ve tried a bunch of different ways and I feel like I’m getting no where.
def listsample():
sample = []
killcode = str("stop")
sample.append(input("enter number"))
while sample[-1] != killcode:
if killcode not in sample:
sample.append(input("enter number"))
elif killcode in sample:
return sample
def printsample(sample):
print(sample)
listsample()
printsample(listsample())
I’ve tried moving stuff around a lot. I didn’t keep my previous trial and error samples. I understand the bare minimum of loops and stuff, this is kind of me trying to figure them out.
I tried doing one of the answers and now it works but it still allows strings to be put into the list. From what I understand, elements in a list are always strings. I attempted to set the input to an integer from the get-go but that causes an error to pop if I put in a string and it stops the code. How would I modify it so it doesn’t allow strings into the input other than ‘stop’ which would then allow the loop to finish? I’ve now tried using a try:except loop which I don’t fully understand but it makes sense to me logically that it should work but if I enter a string it just returns “none”.
def listsample():
sample = []
killcode = "stop"
while 1: # simply loop until stop is recevied!
try:
user_input = int(input("Enter number: "))
if user_input == killcode:
return sample
sample.append(user_input)
except ValueError:
break
def printsample(sample):
print(sample)
printsample(listsample())
Scott Burkhart is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Check if the user entered stop
elsewise add the input to the list:
def listsample():
sample = []
killcode = str("stop")
while 1: # simply loop until stop is recevied!
user_input = input("Enter number: ")
if user_input == killcode:
return sample
sample.append(user_input)
def printsample(sample):
print(sample)
printsample(listsample())
Out:
Enter number: 1
Enter number: 2
Enter number: foo
Enter number: 44444
Enter number: stop
['1', '2', 'foo', '44444']
5
Having to stop the code if a string is input by the user. you can create a custom IntList class (that inherits the list class) that only takes int values. Here’s how you can achieve this:
class IntList(list):
# override the append method
def append(self, value: str): # I have set the type of `value` as str as the input() function returns a string
# check if the value is integer or not
if value.isnumeric():
super().append(value)
else:
raise TypeError("IntList can only have integer values")
Note: The above class stores the numbers as a string and not as integer.
if you want to store as integer you can replace the logic to:
class IntList(list):
# Override the append method to ensure only integers are appended
def append(self, value):
if not isinstance(value, int):
raise TypeError("Only integer values can be appended.")
super().append(value)
This is terminal output for the same:
>>> sample = IntList()
>>> sample.append(10) # this goes okay
>>> sample.append("Hello") # this does not
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in append
TypeError: IntList can only have integer values
Now to use this in your code:
# Custom class IntList
class IntList(list):
# override the append method
def append(self, value):
# check if the value is integer or not
if not isinstance(value, int):
raise TypeError("IntList can only have integer values")
# finally append the value if it is integer
super().append(value)
# your code:
def list_sample():
# create sample
sample = IntList()
# now since no string will be allowed to append,
# kill code or kill command is unnecessary.
while True:
try:
sample.append(input("Enter Number: "))
except TypeError:
pass # since we want to stop inputting.
Remember the input() function always returns a string, if you wanted to use the
IntList
implementation where the numbers are stored as an integer, You need to typecast the value of the input() function. At the same time, the code will throw an error if you try to typecast a string that contains letters to int.
Deep is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Since no one else pointed out the mistake in your code which prevents you from getting desired output, I am listing them below along with the reasons and solution.
elements in a list are always strings
this statement is wrong, list.append
methods adds whatever you provide it to append. The input()
function is the one which returns everything as string.
Focusing on your first code:
def listsample():
sample = []
killcode = str("stop")
sample.append(input("enter number"))
while sample[-1] != killcode:
if killcode not in sample:
sample.append(input("enter number"))
elif killcode in sample:
return sample
def printsample(sample):
print(sample)
listsample()
printsample(listsample())
Problem: When you enter “stop” your while loop terminates and therefore your
sample
list doesn’t get returned.Solution: use
else
clause of along with while loop.
Problem: Strings are also appended, since you have not converted string which input() returns into integer.
Solution: typecaste result of
input()
to int.
After appling above fixes, your code looks like:
def listsample():
sample = []
killcode = "stop" # "stop" is already string, therefore no need to str("stop")
while killcode not in sample:
value = input("enter number: ")
if value.isdigit(): # check if all index of string are digits
sample.append(int(value))
elif value == killcode:
sample.append(value)
else:
print("Enter Integer or 'stop' only!")
else:
return sample[0:-1] # Return all elements execpt last that is 'stop'
def printsample(sample):
print(sample)
printsample(listsample())
def listsample():
sample = []
while True:
user_input = input("Enter a number or 'stop': ")
if user_input == "stop":
break
sample.append(user_input)
return sample
sample = listsample()
print(sample)
SWATHI_23105052 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.