dimanche 29 mars 2020

How to write IF functions in Python when the condition requires the input to be a special character?

I'm trying to build a sample calculator in Python. It's expected output for calculate(2, 3, -) should be -1.

However, I have a hard time defining the operator.

if operator == +: will return a syntax error, but when I do if operator == '+': I need to write something like calcuate(3, 4, '+') to work.

Here are

def calculate(x, y, operator):
    if operator == '+':
        print (x + y)
    elif operator == '-':
        print (x - y)
    elif operator == '*':
        print (x * y)
    elif operator == '/':
        print (x / y)

Is it possible for me to get rid of the required apostrophes?

Aucun commentaire:

Enregistrer un commentaire