Home > Net >  error: "float() argument must be a string or a real number, not list" but list is required
error: "float() argument must be a string or a real number, not list" but list is required

Time:07-24

Working on assignment for intro to python class. We have to write a program for a single line command calculator with operator name instead of sign (can only say 'add' , can't use ' ') and use parsing and tokens. I finally got everything to semi-work (still need to tweak and add things) but I keep getting error saying I can't use float() with lists but my professor said we need to both use parsing and tokens in conjunction with float so I am super lost.

NEW EDITED:

def main():
    calc = input('>')
    tokens = calc.split(" ")
    x = float(tokens[1])
    y = float(tokens[2])
    add(x, y)
    sub(x, y)
    mul(x, y)
    div(x, y)
    abs(x)
def add(x, y):
    print(x   y)
def sub(x, y):
    print(x - y)
def mul(x, y):
    print(x * y)
def div(x, y):
    if y == 0:
        print('Error: Division by zero')
        print('0')
    else:
        print(x / y)
main()

It is now working with the edits suggested (thank you!!) but it is performing all of the operations now instead of only the actual operation that the user enters (when user enters 'add 2 3' it will print the result of adding them, subtraction, multiplication, division, and absolute)

CodePudding user response:

Please add the if statements yourself, since it's an assignment I can't do it for you.

def main():
    calc = input('>')
    tokens = calc.split(" ")
    x = float(tokens[1])
    y = float(tokens[2])

    print(add(x, y))
    print(sub(x, y))
    print(mul(x, y))
    print(div(x, y))
    print(abs(x))
def add(x, y):
    return x   y
def sub(x, y):
    return x - y
def mul(x, y):
    return x * y
def div(x, y):
    if y == 0:
        print('Error: Division by zero')
        return 0
    else:
        return x / y
main()

Output:

>add 4 2
6.0
2.0
8.0
2.0
4.0

CodePudding user response:

Prob. you can try this snippet to see if it can help you:

As the earlier comments expressed the concern that some of the concepts are maybe ahead of your learning - that's fine, it's just presenting another more natural Pythonic way to solve the problem. You will find these may become clear/helpful one day.

def main():
    rules = {'add': add, 'sub': sub, 'mul': mul, 'div': div} # dict to map the operator action

    operator, *tokens  = input('operator num1 num2: ').split()
    print(operator, tokens)
    
    #tokens = list(map(float, input('two numbers now: ').split()))
    #print(tokens)
    
    x, y = map(float, tokens)
  
    result = rules[operator](x, y)
    print(result)
    

def add(x, y):
    return x   y
def sub(x, y):
    return x - y
def mul(x, y):
    return x * y
def div(x, y):
    return x / y

main()

Running Demo:

operator num1 num2: mul 3 4
mul ['3', '4']
12.0
>>> 
  • Related