I'm working on this task in python, but I'm not sure if I'm adding the elements to a list the right way. So basically I'm suppose to create a create_list function the takes the size of the list and prompt the user for that many values and store each value into the list. The create_list function should return this newly created list. Finally the main() function should prompt the user for the number of values to be entered, pass that value to the create_list function to set up the list, and then call the get_total function to print the total of the list. Please tell me what I'm missing or doing wrong. Thank you so much in advance.
def main():
# create a list
myList = []
number_of_values = input('Please enter number of values: ')
# Display the total of the list elements.
print('the list is: ', create_list(number_of_values))
print('the total is ', get_total(myList))
# The get_total function accepts a list as an
# argument returns the total sum of the values in
# the list
def get_total(value_list):
total = 0
# calculate the total of the list elements
for num in value_list:
total += num
#Return the total.
return total
def create_list(number_of_values):
myList = []
for num in range(number_of_values):
num = input('Please enter number: ')
myList.append(num)
return myList
main()
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With