+ 3
Addition of multiple numbers in python
I wrote a code like this def add(*args): sum = 0 for i in args: sum = sum + i return sum print(add(3,4)) I directly given values in the add function call. How can I get values from the user? And also tell me how to print an error message when user enters any alphabet or special character ??
25 Respuestas
+ 4
Check this out:
All greate things are simple,
https://code.sololearn.com/cBLxyszh1Qtj/?ref=app
+ 2
def add(args):
sum = 0
for i in args:
sum = sum + i
return sum
#try like this
a = []
try:
a = list(map(int, input().split()))
except:
print("Please enter Numeric values only")
exit()
print(add(a))
Try thus code and pass space seperated values in single line
Ex input : 1 2 3 4
+ 2
Pardha Saradhi My code requires all the inputs to be in separate lines. If you want the numbers to be in a single line, then try this one:
try: print(add(*map(int, input().split())))
except: print("Please enter a valid input!")
# Hope this helps
+ 2
Wow Shadoff nice way to code it 👍👍
+ 2
Shadoff Thank you ☺️
+ 1
def add(*args):
sum = 0
for i in args:
sum = sum + i
return sum
#try like this
try:
a = int(input())
b = int(input())
except:
print("Please enter Numeric values only")
print(add(a,b))
+ 1
Calvin Thomas Thank you. But when I run that code, I given Many numbers as input but did not get the answer. I don't know what to give to get output. Can you please tell me
+ 1
exit() is used to stop the execution of program at the point where it is used, I have used this so that you can only see the error message that we are providing to user and not the error generated by python.
+ 1
Calvin Thomas thank you
+ 1
try:
def s(*x):
s = sum([float(i) for i in x])
return s
n = input().split()
x = list(map(float,n))
print(s(*x))
except:
print("input error")
# you must input digit separated by space. Ex: 1 2 3
#it's outputting real number
#hope this help
+ 1
THIS IS THE CODE FOR ADDITION FOR TWO NUMBERS.
https://code.sololearn.com/cm49144FHOA6/?ref=app
+ 1
BR0 V CAN'T SEND SCREEN SHOTS IN SOLOLEARN.
0
Pariket where can I use that input () function
0
Or if you want multiple inputs you can even use list for that
0
Sumit Kumar When I entered alphabets, it is not showing any error message
0
Pardha Saradhi Here's a possible solution:
def add(*args): return sum(args)
inp = []
try:
while 1: inp.append(int(input()))
except ValueError:
print("Please enter a valid input!")
exit()
except EOFError: print(add(*inp))
# Hope this helps
0
Pardha Saradhi
Run the code and see the output window you will find the error message for user followed by the error message generated by python
Hope this helps 😊
0
Sumit Kumar I already did that. I given 6 and t as inputs. It shows valueError
0
Actually I don't know how to send screen shot in sololearn , if anyone know plz tell in that way Ican clarify the things better👍
0
Sumit Kumar Yeahh I got it. Thank you
Can you please tell me what is exit() function