Need Help Dealing with inputs [duplicate] - python

This question already has answers here:
How to append multiple values to a list in Python
(5 answers)
Closed 7 months ago.
Begginer Question, So i have this problem where i receive a lot of inputs in different lines like:
Inputs:
1
2
0
2
1
And i want to sum them or store them in any kind of list to Sum them latter, how can i do this?
I mean, i could store a variable for each one of them like:
a1 = int(input())
a2 = int(input())
ax = int(input())
....
and then
result = a1+a2+ax...
print(result)
but that's not pratical. Someone can explain me on how to store and sum them in a list?
i think that i could do something like this too
x = int(input())
and use
x += x

Just use python lists:
inputlist = []
for i in range(5):
inputlist.append(int(input))
result = sum(inputlist)
Note, I just put a 5 there to ask for 5 values. Ask however many inputs you want.

you could use a while loop, or a for loop for it. If you are provided the number of inputs in advance in a variable x, you can start with a for loop.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
answer = 0
for i in range(x):
answer += int(input())
print("Answer is", answer)
If you do not know the amount of inputs in advance, you can implement a while loop that will take input until a non-integer input is given.
answer = 0
while True:
x = input()
try:
x = int(x) # Tries to convert the input to int
except ValueError: # If an error occurs, ie, the input is not an integer.
break # Breaks the loop and prints the answer
# If all goes fine
answer += x
print("Answer is", answer)
And obviously, we also have a classic alternate to all this, which is to use python list, these can store numbers and we can process them later when printing the answer. Although, I would have to say if the number of input is large, then the most efficient manner is to use either of the above solution due to their memory footprint.
x = int(input("Number of Inputs> ")) # If you know the certain number of inputs
# that you are going to take, you can directly replace them here.
inputs = []
for i in range(x):
inputs.append(int(input()))
print("Answer is", sum(inputs))

I'm also a beginner, but here's a solution I came up with:
new_list = []
for entry in range(10):
new_list.append(int(input()))
print(sum(new_list))

Related

Why this WHILE loop does not end? [Python] [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
im trying to create a multiple values calculator in Python, using While, For/In sentences with lists
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == 1:
out == 1
#In theory if out == 1 the while loop should end and go to:
for add in numbers:
add = numbers
print(add)
I tried using While Not sentence, but i get an obvius mistake. I suppose this is a pretty dumb error of comprehention i have, but i can't really get what am i doing wrong. I'll be very glad if u help me with this.
First of all, variable assignment should be done with = not ==. Your problem is that in the second input() (where you let user choose will he/she stay or exit), you need to convert the input to int from string first, OR check by the string representation of the number (fail-safe):
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
out = 1
However, best way to break out a loop is to use break:
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
if out2 == '1':
break
Apart from the errors pointed out in the other 2 answers, you are getting input from the user as a str and not converting it to an int.
So it never hits the if condition and therefore your program doesn't end.
Please try this
numbers = []
out = 0
while out == 0:
numbers.append(int(input('Add a number: ')))
out2 = input('''[0]To keep adding numbers
[1]To add and leave: ''')
print(type(out2))
if int(out2) == 1: # Convert the out2 to an int here
print(f" Inside if condition")
out = 1 # Use an assignment operator here

A way to get python to receive input and sum it? [duplicate]

This question already has answers here:
Loop that adds user inputted numbers and breaks when user types "end"
(4 answers)
How to sum numbers from input?
(2 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
sorry for the stupid question, but I can't get out of this thing in any way, I'm a beginner.
I need to write a code that asks the user to write a series of int one at the time using a while function. When the user has inserted all the numbers, to stop the series he'll write a specific string. When it's done, I need the code to print the sum and the average of all the numbers inserted.
The user can't insert them all in one time, he needs to enter one at the time.
I tried something like this: but there's no way it'll work. Implementing items in a list and then operate on the list is possible, but I had no idea on how to do that more easily than summing every element each time.
(my initial code:)
count = 0
total = 0
while():
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + number
print(total)
print(total / count)
Don't mind about data being a string or an int, as long as it's just an error that IDLE would tell me. I just would like to know what's logically wrong in my code.
Thank you in advance.
You were really close, I made a couple of changes - firstly I changed while(): to while True:, so that the loop runs until break is hit. Secondly I altered total = total + number to total = total + int(new_number) - corrected variable name and convert string returned by input() to an int. Your logic is fine.
Corrected Code:
count = 0
total = 0
while True:
new_number = input('> ')
if new_number == 'Done' :
break
count = count + 1
total = total + int(new_number)
print(total)
print(total / count)
Using a list is actually not that hard. Here's how:
Firstly make the corrections from CDJB's answer.
Create an empty list. Add each new_number to the list. Use sum() and len() to get the total and count.
nums = []
while True:
new_number = input('> ')
if new_number == 'Done':
break
nums.append(int(new_number))
total = sum(nums)
count = len(nums)
print(total)
print(total / count

Finding the next entity in a list python

I am relatively new to python and I have searched the web for an answer but I can't find one.
The program below asks the user for a number of inputs, and then asks them to input a list of integers of length equal to that of the number of inputs.
Then the program iterates through the list, and if the number is less than the ToyValue, and is less than the next item in the list the variable ToyValue increments by one.
NoOfToys=0
ToyValue=0
NumOfTimes=int(input("Please enter No of inputs"))
NumberList=input("Please enter Input")
NumberList=NumberList.split(" ")
print(NumberList)
for i in NumberList:
if int(i)>ToyValue:
ToyValue=int(i)
elif int(i)<ToyValue:
if int(i)<int(i[i+1]):
NoOfToys=NoOfVallys+1
ToyValue=int(i[i+1])
else:
pass
print(NoOfVallys)
Here is an example of some data and the expected output.
#Inputs
8
4 6 8 2 8 4 7 2
#Output
2
I believe I am having trouble with the line i[i+1], as I cannot get the next item in the list
I have looked at the command next() yet I don't think that it helps me in this situation.
Any help is appreciated!
You're getting mixed up between the items in the list and index values into the items. What you need to do is iterate over a range so that you're dealing solidly with index values:
NoOfToys = 0
ToyValue = 0
NumOfTimes = int(input("Please enter No of inputs"))
NumberList = input("Please enter Input")
NumberList = NumberList.split(" ")
print(NumberList)
for i in range(0, len(NumberList)):
value = int(NumberList[i])
if value > ToyValue:
ToyValue = value
elif value < ToyValue:
if (i + 1) < len(NumberList) and value < int(NumberList[i + 1]):
NoOfToys = NoOfVallys + 1
ToyValue = int(NumberList[i + 1])
else:
pass
print(NoOfVallys)
You have to be careful at the end of the list, when there is no "next item". Note the extra check on the second "if" that allows for this.
A few other observations:
You aren't using the NumOfTimes input
Your logic is not right regarding NoOfVallys and NoOfToys as NoOfVallys is never set to anything and NoOfToys is never used
For proper Python coding style, you should be using identifiers that start with lowercase letters
The "else: pass" part of your code is unnecessary

Calculate sum of list of values entered by users [duplicate]

This question already has answers here:
How do I add five numbers from user input in Python?
(5 answers)
Closed 6 years ago.
I'm trying to help my son who's got some Python homework from school...and I haven't coded since school and this is my first evening on python so forgive the dumb question.
Using a "For" statement I need to prompt the user to enter 10 numbers. When the entries have ended, I need to display the sum. I know I need to do something linking newsum/oldsum/+ value entered but I'm stuck. All help gratefully received.
Here's where I've got to:
total=int
runningtotal=int
thisinput=int
n=0
for num in range (1,11):
runningtotal=thisinput+n
print("enter number",num)
n=int(input())
thisinput=n
print(runningtotal)
The answer is:
inputs_sum = 0
for x in range(10):
inputs_sum += int(input('Enter number:'))
print('The sum is {}'.format(inputs_sum))
Enjoy!
In python3.x, using your code as a working model, probably something like this:
runningtotal=0
for num in range(10):
thisinput = input("enter number: ") # If using python2.x change input to raw_input
runningtotal+=int(thisinput)
print(runningtotal)
Another answer (was deleted) used list.append() to add numbers to list and sum the list elements like so:
num_list = []
for num in range(10):
thisinput = raw_input("enter number: ")
num_list.append(int(thisinput))
print sum(num_list)

How to read a specific number of integers and store it in a list in python?

Lets suppose I want to first input the total number of integers I am going to enter.
N = 5, I must be able to read exactly 5 integers and store it in a list
for i in range(5):
lst = map(int, raw_input().split())
doesn't do the job
In most primitive way, you can do it in following way.
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]
We can help more if you tell us the context in which you are asking the problem. I doubt if you are using it for some competitive programming problem.
Actually, problem in your code is that you are reading a line and making list from it. But you are doing this FIVE times. Also, you can read lot more than five numbers if they are in single line.
Sa far as I understand, you need the following
lst=[]
for n in range(5):
lst.append(int(raw_input("Input a number: ").split()))
print repr(lst)
inp = raw_input # Python 2.x
# inp = input # Python 3.x
def get_n_ints(prompt, n):
while True: # repeat until we get acceptable input
s = inp(prompt)
try:
vals = [int(i) for i in s.split()]
if len(vals) == n:
return vals
else:
print("Please enter exactly {} values".format(n))
except ValueError:
# a string couldn't be converted to int
print("Values need to be integers!")

Categories

Resources