How can I sum a list of numbers? - python

My program needs to read a set of integers from the user and store them in a list. It should read numbers from the user until the user enters 0 to quit. Then it needs to add them up and display the sum to the user. If the user types anything that is not an integer, it needs to display an error to the user.
I'm having a hard time figuring out how to make a list that the user can infinitely input numbers into.
From what I have tried to do and looked up, I've only been able to make a defined list and make a program that takes in a specific amount of inputs.
This is what I have. Obviously, it doesn't work, but it shows what I'm going for.
n, ns = 0, 0 # count of numbers, sum of numbers
print("Enter numbers or any other 0 to quit.")
while(1):
grades = input("enter = ")
if (int):
ns += int
n += 1
else:
if (0):
print(ns)
break

Use this:
list_of_nums = []
loop = True
while loop == True:
try: num = int(input("Enter Integer: "))
except ValueError: num = "invalid"
if num == "invalid": print("\nPlease Print A Valid Integer!\n");
elif num != 0: list_of_nums.append(num)
else: loop = False
print("\nSum of Inputed Integers: " + str(sum(list_of_nums)) + "\n")

Python 3
lists=[]
while(True):
i=int(input("Enter The Input"))
if i==0:
break
else:
lists.append(i)
print(lists)

Related

how to sort a list in a while loop

I want to write a program which reads numbers continuously from the user (one at a time), until the user enters "0"
and then the program returns the smallest number in that inputs. I am having trouble sorting out.
This is my code so far:
while True:
number = []
number = input("Please enter a number ")
if number == "0":
break
number.sort()
x = number[0]
return x
You overwrite your number at each step, this cannot work. You should keep track of the min value instead:
min_value = None
while True:
number = int(input("Please enter a number ")) # no type check here
if number == 0:
break
if number is None or number < min_value:
min_value = number
print(min_value)
You can make a list of your entered numbers appending them and then finding the minimum value using the numpy module. For example:
import numpy as np
while True:
number_list = []
number = input("Please enter a number ")
number_list.append(number)
if number == "0":
break
number_array = np.array(number_list)
minval = np.min(number_array[np.nonzero(number_array)])
So that you can find the minimum value of the array, excluding the "0" you entered at the end.

How to accept user input of a sequence?

I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x

How to get Python functions to calculate maths operations?

I have this assignment to create a program that asks user to input any positive integer repeatedly or type anything else to end and generate the sum, count and average of the numbers. My teacher wants all the code in these this structure with these three def’s only
This is the code I have, any suggestions on how to get it to work?
def calcAverage(total,count):
sum = 0
count = 0
average = sum / count
def inputNumber(message):
while True:
try:
userInput = int(input(message))
count = count + 1
sum = sum + entry
if userInput < 0:
raise ValueError
except ValueError:
main()
else:
return userInput
break
entry = inputNumber('Type any positive integer, anything else to quit')
def main():
print('Sum')
print(sum)
print('Average')
print(average)
print('Total Numbers')
print(count)
The question is not well explained + we don't really get what the boundaries are. Moreover, you should clearly state what is not working. Now, to give you some hint, this is how I would do it:
input = None
L = list()
while True:
try:
input = int(input('Type any positive integer, anything else to quit: '))
if input < 0:
break
else:
L.append(input)
except:
break
S = sum(L)
I think you don't need to use exceptions here. Condition statements would make it clearer.
I would put the valid inputs in a list until the user make a invalid input. When it happens, just get out of your while loop using a break statement and return the result.

I am trying to get my program to take only integers and stop when the user presses 0

So the code before behaved properly before my "while type(number) is not int:" loop, but now when the user presses 0, instead of generating the sum of the list, it just keeps looping.
Would really appreciate some help with this! Thank you!
List = []
pro = 1
while(pro is not 0):
number = False
while type(number) is not int:
try:
number = int(input("Please enter a number: "))
List.append(number)
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
ans = 0
print(Sum)
Actually, this should keep looping forever for all numbers the user may input, not just zero.
To fix this, you can just add this break condition after (or before, it doesnt really matter) appending:
number = int(input("Please enter a number: "))
List.append(number)
if number == 0:
break
So I got it to work, when written like this:
List = []
pro = 1
while(pro is not 0):
while True:
try:
number = int(input("Please enter a number: "))
List.append(number)
break
except ValueError:
print("Please only enter integer values.")
if(number == 0):
Sum = 0
for i in List:
Sum = i + Sum
pro = 0
print(Sum)
But I don't really understand how this is making it only take int values, any clarification would be really helpful, and otherwise thank you all for your help!
I'm guessing that you want to end while loop when user inputs 0.
List = []
pro = 1
while pro is not 0:
try:
number = int(input("Please enter a number: "))
List.append(number)
# This breaks while loop when number == 0
pro = number
except ValueError:
print("Please only enter integer values.")
Sum = 0
for i in List:
Sum += i
print(Sum)
EDIT: I have also cleaned the unnecessary code.
Put if number == 0: inside while type(number) is not int: loop like this:
List = []
while True:
try:
number = int(input("Please enter a number: "))
if number == 0:
Sum = 0
for i in List:
Sum = i + Sum
print(Sum)
break
List.append(number)
except ValueError:
print("Please only enter integer values.")

Stuck with this

I am trying to write a program that will add together a series of numbers that the user inputs until the user types 0 which will then display the total of all the inputted numbers. this is what i have got and im struggling to fix it
print ("Keep inputting numbers above 0 and each one will be added together consecutively. enter a and the total will be displayed on the screen. have fun")
number = input("Input a number")
sum1 = 0
while number >= 1:
sum1 = sum1 + number
if number <= 0:
print (sum1)
Here is a more robust way to input the number. It check if it can be added. Moreover I added the positive and negative number.
# -*-coding:Utf-8 -*
print ("Keep inputting numbers different than 0 and each one will be added together consecutively.")
print ("Enter a and the total will be displayed on the screen. Have fun.")
sum = 0
x = ""
while type(x) == str:
try:
x = int(input("Value : "))
if x == 0:
break
sum += x
x = ""
except:
x = ""
print ("Please enter a number !")
print ("Result : ", sum)
If you're using Python 3, you will need to say number = int(input("Input a number")) since input returns a string. If you're using Python 2, input will work for numbers but has other problems, and the best practice is to say int(raw_input(...)). See How can I read inputs as integers? for details.
Since you want the user to repeatedly enter a number, you also need an input inside the while loop. Right now it only runs once.

Categories