0
How to add input numbers and get total addition result as i go along in Python?
For example... Say i input 2 Then i input 3 I would get 5 Now if i again say, 3 I should get 8.. and so on... How do i do that..
16 Réponses
0
# try something like this. Input -1 to stop
result = 0
while (True):
num = input()
if num == '-1':
print('-'*5)
break
result += int(num)
print(result)
+ 3
Ramprasad Saha ,
before we can help you, you should show us your attempt first. if you have not done a try by yourself upto now, please do so. put your code in playground and link it here.
thanks!
+ 1
You cannot do that in Sololearn. All inputs must be submitted in the submit popup. It is very limiting, but that is the way it is. No user interaction at all, except at the start.
If you want to practice coding Python from your phone, you could try Pydroid 3. It is a better alternative.
+ 1
Bob_Li i know bro..
I actually asked help for a project i am doing on pydroid3.
+ 1
oh. my mistake.
Yes, do a while loop.
create a global variable to store the result.
Also make exit conditions to break the loop.
Try this:
#variables
sum = 0
user_in = 0
#while loop (input 'q' to quit)
while user_in != 'q':
user_in = input('Input a number, or input q to quit.\n')
#It is always a good idea to have try/except blocks to handle errors in user input
try:
#This if block is used to handle the 'q' input
if user_in == 'q':
print('Sum = ', sum)
print('Exiting program')
break
#This part handles the normal correct input
sum += int(user_in)
print('Sum = ', sum)
#Except is used to handle inputs that cannot be converted to int
except:
print('Your input cannot be converted to integer.')
+ 1
Bob_Li thanks bro✌️
0
With a loop.
0
Simon Sauter i tried using...
while True:
But i dont know how to store each input value and add it cosequetively...
0
You need a closing condition.
Create a variable and add the new value to it. Like this.
sum = 0
#your loop with a condition :
sum += newValue
print(sum)
0
Sushil Prasad Thanks buddy,, it works great.
0
while True:
try:
print(int(input())+int(input()))
exit_code=input("Do you want exit?\n").lower()
except:
continue
if exit_code in ("yes", "yeah"):
break
Because first I make a infinite while loop, then I make total addition of the number you put, if you not put a number, the while loop is repeated, later the numbers, if you want exit of the code, you put "yes" or "yeah", if you don't want exit of the code, put anything.
Good luck 👍
0
Glad to help.
If only this code could work in Sololearn...
0
Yes, in Sololearn you have to submit your inputs as a list. The end result is the same, but the interactivity is gone.
- 2
Lothar I tried buddy manytimes...
But failed..
So i asked for help in here
- 2
num1 = int(input())
num2 = int(input())
print(num1 + num2)