Home > Software engineering >  Can anybody help and explain this why python gives value error for below problem
Can anybody help and explain this why python gives value error for below problem

Time:08-19

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)

Im trying to solve sum of 1d array question from leetcode, while im appending the list im getting the value error, can anyone please help me to solve the error, and explain this why im getting this issue.

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)

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)
  • Related