0

I am trying to create a calculator program that takes user input and stores it in a list and perform the calculation based on their selection. However, I keep running across an error for line 31 saying

TypeError: 'float' object cannot be interpreted as an integer.

Here is the code:

import math

def printIntro():
    print("This is a simple calculator.")
print("Select an operation:\n1) Add\n2) Subtract\n3) Divide\n4) Multiply")

while True:
    operator = input("Enter your choice of + - / *: \n")

    if operator in('+', '-', '/', '*'):
        #continue asking for numbers until user ends
        #store numbers in an array

        list = []
        num = float(input("What are your numbers?: "))
        for n in range(num):
            numbers = float(input("What are your numbers?: "))
        list.append(numbers)
        if n == '':
            break

        if operator == '+':
            print(add(list))

        if operator == '-':
            print(subtract(list))

        if operator == '/':
            print(divide(list))

        if operator == '*':
            print(multiply(list))
    else:
        break
bad_coder
  • 11,289
  • 20
  • 44
  • 72
Varioli
  • 9
  • 2
  • 1
    An iterator must be of type integer hence this line fails `for n in range(num):` since you explicitly convert `num` to float. Use `int()` instead. – NotAName Apr 17 '21 at 03:49
  • There are a number of issues that I noticed with your code. Some of them are mentioned below so I'll just add one concern from a quick read. Your prompt is confusing. When you ask "what are your numbers?" that triggers a request for multiple numbers. Are these comma separated? Space separated? Regardless of what how it is, `float()` will not work. You can't take a float of a string that is itself multiple values. You need to parse that into separate elements first. For example, trt `float("5, 10")` – astrochun Apr 18 '21 at 06:46
  • Do you follow a specific [tutorial](https://pythonguides.com/make-a-calculator-in-python/), book, etc? Pay attention to the __indents__ (`print` on line 5) and make code-reading/debugging easier when keeping loops short, e.g. __extract the loop body__ into a function. – hc_dev Apr 18 '21 at 07:37

2 Answers2

1

Python's range method accepts an integer.

The error is due to the fact that you convert the input to float in num = float(..) before giving it to range(num).

I think in the line where you try to get the number from input causes it:

num = float(input("What are your numbers?: "))

It should work with (I also fixed the prompt message):

num = int(input("How many numbers you have?: "))
hc_dev
  • 8,389
  • 1
  • 26
  • 38
srknzl
  • 776
  • 5
  • 13
0

for n in range(int(num)): cast num as int inside the for loop such as this. There is a similar comment to this above but here is the fixed code.