Output screen:
enter the number of elements:3
1
23
3
Traceback (most recent call last):
File "<string>", line 18, in <module>
ValueError: invalid literal for int() with base 10: ''
>
Code :
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input())
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
I'm trying to solve sum of 1d array question from Leetcode, while I'm appending the list I'm getting the value error. Why am I getting this issue?
CodePudding user response:
Just a SLIGHT modification
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
ele =int(input("")) # <<============= HERE
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)
CodePudding user response:
Your Code works fine.
The problem may come when you put input anything other than numbers. You may have pressed the "enter" button without any number in your error case. That's why the error said '' in the end.
To avoid such an error, you can write a try-block like the below.
arr =[]
def runninsum(arr):
srr = []
temp = 0
summ = 0
for i in arr:
temp = i
summ = summ temp
srr.append(summ)
return srr
n = int(input("enter the number of elements:"))
for j in range(0, n):
while True:
user_input = input('Enter an int element: ')
try:
ele = int(user_input)
except ValueError:
print(f"Invalid integer '{user_input}', try again")
else:
break
arr.append(ele)
print(arr)
num = runninsum(arr)
print(num)