+ 1

python def calc _default_ add(x, y, op )

I got (SyntaxError: invalid syntax) with this exercise : Define the function calc_default_add() which, when given two numeric inputs and the string "add" or "sub" either adds or subtracts the two numbers appropriately. If the string is not provided as a third parameter, make the default operation add. If any other operation is provided as the third parameter, make sure you print the string"Valid operation: add, sub". def calc_default_add(x, y, op): if (op == "add" or op == None"): print(x = y) elf(op == "sub"): print(x-y) else: print("Valid operations : add, sub") This is what I did: def calc_default_add(x, y, op=def calc_default_add(x, y, op="add"): # Here I got (SyntaxError: invalid syntax) if op != "add" or op != "sub": print("Valid operations: add, sub") elif op == "add": return int(x + y) elif op == "sub": return int(x - y) else: return Nonead

2nd Jul 2019, 10:09 AM
Sundas Alduraihem
Sundas Alduraihem - avatar
3 Réponses
+ 2
The function header should be like: def calc_default_add(x, y, op='add'): This way you can specify 3 parameters or if you specify only 2, then the third one is defaulted to 'add'.
2nd Jul 2019, 10:51 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Your major logic problem is in your line: if op != "add" or op != "sub": The problem is this; if someone inputs "add", it satisfies the '!= "sub"' section of your if statement, so it prints your "Valid operations..." string. You need to have if op != "add" and op != "sub": to stop this happening. Now it will only return True if the input is different to "add" *and* "sub". Edit: I didn't read your question correctly and I jumped ahead a bit, sorry!
2nd Jul 2019, 11:22 AM
Russ
Russ - avatar
0
Thanks alot. I appreciate your help.
19th Sep 2019, 8:06 AM
Sundas Alduraihem
Sundas Alduraihem - avatar