Reputation: 158
I am noob and I am working on this python project and i cant get the first input entered by the user in a array my code. Thanks in advance Here is my code:
def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
print("Invalid input")
while user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
break
ask()
Upvotes: 1
Views: 66
Reputation: 21609
You do not add your initial input to the array. Instead you enter the loop and ask for another input and check then add that to the array. You should ask for all inputs within the loop, as this means you only need one raw_input
and one check for the done value.
A common way to do this is to go into an infinite loop and only exit when you read the value done
. Like so
def ask():
user_input_array = []
while True:
user_input = raw_input("Enter a number: ")
if user_input == 'done':
break
try:
user_input_array.append(int(user_input))
except ValueError:
print("Invalid input")
print ("done")
print ('Count: ', len(user_input_array))
print (user_input_array)
ask()
Note that this achieves the desired effect with no repetition. You also don't need to keep a count of how many elements you added, as the list has a len
function which will tell you that.
Upvotes: 0
Reputation: 752
def ask():
user_input = raw_input("Enter a number: ")
user_input_array = []
count = 0
quits = 'done'
while user_input != quits:
user_input = raw_input("Enter a number: ")
try:
if type(user_input) == str:
num = int(user_input)
user_input_array.append(num)
count = count + 1
except:
if user_input == quits:
#user_input_array.remove('done')
print ("done")
print ('Count: ', count)
print (user_input_array)
else:
print("Invalid input")
ask()
Upvotes: 0
Reputation: 43078
That is because you never put it in there.
def ask():
user_input = raw_input("Enter a number: ")
user_input_array = [user_input] # Create the list with the original input
...
With the above, the first thing entered by the user is placed in the list when the list is created. You might want to do your checks before this
Upvotes: 1