Elijah D-R Elijah D-R - 3 months ago 12
Python Question

Error with calculator type program in python

numbers=[]
while True:
print('Input Number '+str(len(numbers)+1)+' (or nothing to close):')
number=input()
numbers=numbers+[number]
if number=='':
print('What do you want to do?')
answer=input()
break
if answer==mean:
mean
def mean():
end_mean=reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mean)


I am trying to make a calculator type program in python which allows you to enter a list of numbers and then select what you do with them. The script above is only the beginning but when i enter the numbers and type in 'mean' when it asks me what to do, it ends the script and shows nothing. I am new to python so please be forgiving as such in the answers.

Edit 2 -

numbers=[]
def mean():
end_mean=reduce(lambda x, y: x + y, numbers) / len(numbers)
print(end_mean)
while True:
print('Input Number '+str(len(numbers)+1)+' (or nothing to close):')
number=input()
if number=='':
print('What do you want to do?')
answer=input()
if answer=='mean':
mean()
else:
numbers=numbers+[int(number)]


This is my improved script, however it says that 'reduce' is not defined:

Traceback (most recent call last):
File "E:/Python/calc.py", line 12, in <module>
mean()
File "E:/Python/calc.py", line 3, in mean
end_mean=reduce(lambda x, y: x + y, numbers) / len(numbers)
NameError: name 'reduce' is not defined


P.S. sorry about me not removing the break, i have not, as people have said, understood what it really does.

Answer

May be this will help you.

numbers=[]

def means():
    end_mean = reduce(lambda x, y: x + y, numbers) / len(numbers)
    print(end_mean)

while True:
    print('Input Number '+str(len(numbers)+1)+' (or nothing to close):')
    try:
        number= int(input())
        numbers.append(number)
    except:
        print('What do you want to do?')
        answer = input()
        if answer == "mean":
            means()
        else:
            break

What have I changed from your Code?

  • Added a try-except block. This is added so that it can handle the case when you passed '' as input.
  • cast input to int before passing to number, as you need int value to calculate mean, not string values.
  • You are making a list from the input and then adding to the previous list, which is unnecessary and inefficient. I replace it with numbers.append(number)
  • The unnecessary break statement removed. break is used to get out from the loops. As you use break, you will never see the later statements executed.
Comments