after much google'ing and note searching I have yet to come upon an answer for making this List of mine work, if you do answer could you explain what I was doing wrong because this problem is determined to not let me work. code:
def main():
x = int(input("Enter a number (0 to stop) "))
y = x
l = []
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l = [x]
print(l[x])
main()
I thought I was supposed to initialize the list outside of the loop, and in the loop I thought it would take whatever X is inputted as and store it to later be printed out after it, but that wasn't the case. Any pointers?
You would need to append to the list each time:
def main():
x = int(input("Enter a number (0 to stop) "))
l = [x] # add first x, we will add to the is list not reassign l inside the loop
while x != 0:
x = int(input("Enter a number (0 to stop) "))
l.append(x) # append each time
print(l) # print all when user enters 0
l = [x]
reassigns l
to a list containing whatever the value of x
is each time through the loop, to get all numbers you have to append to the list l initialised outside the loop.
You could also use iter
with a sentinel value of "0":
def main():
l = []
print("Enter a number (0 to stop) ")
for x in iter(input,"0"):
print("Enter a number (0 to stop) ")
l.append(int(x))
print(l)