Reputation: 3801
I want to write 2 functions. One function that takes input from a user and adds it to a list. The 2nd function takes the list returned from the 1st function and prints out each element separated by a space. I think I am close, but something isn't right. Typing -999 doesn't stop the loop, and I can't tell if I am calling the functions correctly...
Any ideas?
def listFunc():
num = 0
list1 = []
while num != -999:
x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
return list1
def formatFunc(y):
final = str(y)
' '.join(final)
print(final)
formatFunc(listFunc())
Upvotes: 1
Views: 85
Reputation: 1703
You are calling the functions correctly if you intend on printing the inputs of listfunc. However the inputs will not be saved to a variable in global scope and will thus be locked out from any future use.
Additionally, listfunc currently does no input validation. It is possible to input any strings in the input. The while loop doesn't end because the condition in the while is never met. Rewriting it according to your conditions yields:
def listfunc():
someList = []
while True:
x = input("Enter a number, exit to quit")
if 'exit' in x.lower():
break
elif x.isdigit():
someList.append(x)
else:
print("Input not recognized try again")
return someList
def formatFunc(v):
print(''.join(str(i) + ' ' for i in v)
Do you see why this works?
Upvotes: 1
Reputation: 10960
It should be the same variable used in while loop.
num = int(input('Enter a number, -999 to quit: '))
if num != -999:
list1.append(num)
and
# final = str(y) This is not required, why cast list as str
final = ' '.join(final)
Upvotes: 2
Reputation: 926
x = int(input('Enter a number, -999 to quit: '))
list1.append(x)
num=x
will work!
Upvotes: 1