How to add elements to a List in python?
You must convert inputs to integer. input()
returns a string object. Just do
number_of_values = int(input('Please enter number of values: '))
And with every input you want to use as integer.
In main
you created empty list, but didn't assign create_list
result to it. Also you should cast user input to int
:
def main():
number_of_values = int(input('Please enter number of values: ')) # int
myList = create_list(number_of_values) # myList = function result
total = get_total(myList)
print('the list is: ', myList)
print('the total is ', total)
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for _ in range(number_of_values): # no need to use num in loop here
num = int(input('Please enter number: ')) # int
myList.append(num)
return myList
if __name__ == '__main__': # it's better to add this line as suggested
main()
First Problem is you are not passing myList
to create_list
function, so myList
inside of main is not going to get updated.
If you want to create a list inside the function and return it, and then get a total for that list, you need to first store the list somewhere. parse the inputs as integer, also, always do if __name__ == '__main__':
. The Following code should work and print the correct result :)
def main():
number_of_values = int(input('Please enter number of values: '))
myList = create_list(number_of_values)
print('the list is: ', myList)
print('the total is ', get_total(myList))
def get_total(value_list):
total = 0
for num in value_list:
total += num
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = int(input('Please enter number: '))
myList.append(num)
return myList
if __name__ == '__main__':
main()
An alternative method to the posted solutions could be to have one function that creates your said list and finds the total of that list. In the solution, the map function goes through all the values given to it and only keeps the integers (The split method is used to remove commas and spaces from the values). This solution will print your list and values, but will not return any said value, so it will produce a NoneType, if you were to examine the function at the end.
def main():
aListAndTotal()
#Creates list through finding the integers and removing the commas
#For loop iterates through list and finds the total
#Does not return a value, but prints what's stored in the variables
def aListAndTotal():
myList = map(int, input("Please enter number of values: ").split(","))
total = 0
for num in myList:
total += num
print ("The list is: ", myList)
print ("The total is: ", total)
if __name__ == "__main__":
main()