I am new to the python and My program is a simple addition program where it can add any number input by user(int or float) and the loop stops on entering q. Now my problem is that I keep getting "ValueError", every time I enter some numbers and then enter q to stop.
I have used eval() function to determine the datatype of the input data entered. and i have got my addition inside an infinite while loop that breaks on entering q.
This is my code:
sum,sum_i,c=0,0,0
sum_f=0.0
print("Enter q/Q to stop entering numbers.")
while True:
a=input("Enter number: ")
try:
t= eval(a)
print(type(t))
except (NameError, ValueError):
pass
if(type(t)==int):
sum_i=sum_i+int(a)
c=c+1
elif(type(t)==float):
sum_f=sum_f+float(a)
c=c+1
elif (type(t)==str):
if (a=='q'or a=='Q'):
break
else:
print("Invalid data entered. Please enter a number to add or q/Q to quit. ")
sum= sum_i+ sum_f
print("You have entered ",c," numbers and their sum is: ",sum)
My output is supposed to provide the sum of the numbers entered on entering q, but this is what i get:
Enter q/Q to stop entering numbers.
Enter number: 3
<class 'int'>
Enter number: 5.5
<class 'float'>
Enter number: 12
<class 'int'>
Enter number: q
Traceback (most recent call last):
File "/home/netvarth/py test/sum.py", line 14, in <module>
sum_i=sum_i+int(a)
ValueError: invalid literal for int() with base 10: 'q'
import ast,ast.literal_eval()instead ofeval(), for security reasonseval()on raw input from the user. The user can just input something likesys.exit(0)and shutdown your systemeval('q')->NameError;tremains what it was before. If it wasint, you will tryint('q')which yields yourValueError.