Trying to append an input number in a list function is returning none

Question:

I need to return a list of numbers input by the user.

I have tried to insert an empty list and then using the .append function to append the input value to the list.

def ask_a_number():
    trials = []
    playernumber = int(input('Guess a number: '))
    trials = trials.append(playernumber)
    return playernumber, trials
ask_a_number()

Lets say I want to input 5.
So I want the function to return 5 and also a list trials = [5].
Next time when I input 10, the function should return trials = [5,10].

Asked By: Prashant Mishra

||

Answers:

Change

trials = trials.append(playernumber)

to

trials.append(playernumber)

Since list.append returns None (it alters the state of trials instead) and you reassign its return value to trials, you get None in your returned tuple.

Answered By: Paul Rooney

append() doesn’t return anything. It is designed to do in-place modification. So just do the following:

def ask_a_number(trials=None):
    trials = trials or []
    playernumber = int(input('Guess a number: '))
    trials.append(playernumber)
    return playernumber, trials
ask_a_number()

I’ve also added a default value for trials so that if you want to do this in a loop, you can like so:

trials = []

for i in range(6):
    player, trials = ask_a_number(trials)
Answered By: C.Nivs
 def ask_a_number():
       trials = []
       while True:
           playernumber = int(input('Guess a number: '))
           trials.append(playernumber)
           if playernumber==0:
             break
       print(playernumber, trials)
       return 
 ask_a_number()
Answered By: Sun Voyager
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.