Help me with a thing I am trying to do by myself?

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
Just something I’m doing at home

<In what way does your code behave incorrectly? Include ALL error messages.>
Line 13 SyntaxError: ‘return’ outside function

<What do you expect to happen instead?>
I am trying to return the final number for an addition

```python

print “Hello and welcome to Alfie’s calculator Alpha Version One Point Oh”

first_num = int(raw_input(“What is your first number?”))
print “Please use ‘add’ or ‘subtract’”
operation = (raw_input(“Write the operation you would like to use.”))
second_num = int(raw_input(“What is your second number?”))

final_num_add = first_num + second_num
final_num_subtract = first_num - second_num

if len(first_num) > 0 and not first_num.isalpha() and len(operation) > 0 and not operation.isalpha() and len(second_num) > 0 and not second_num.isalpha():
if operation == add:
return final_num_add
elif operation == subtract:
return final_num_subtract
else:
return “error: wrong operation input”
else:
return “error: incorrect characters for num input”

<do not remove the three backticks above>

We cannot use return outside of a function body. It is possible to write a switch statement inside a function (in JavaScript):

function operate(a, b, f) {
    switch (f) {
    case 'add': return a + b;
    case 'subtract': return a - b;
    default: return "error: wrong operation input";
    }
}

console.log(operate(first_num, second_num, operation));

It won’t be necessary to test for isalpha() since the input is already cast to int(). This operation will raise a ValueError exception if their is any non-numeric value in the input. The thing to do is create a utility function to get numeric inputs:

def numeric_input(arg):
    while True:
        try:
            return int(raw_input("Enter your %s operand:" % arg))
        except ValueError:
            print "Value Error: try again"

Usage

first_num = numeric_input('first')
second_num = numeric_input('second')
operation = raw_input("Enter 'add' or 'subtract' as operation.")

Since we should technically allow any signed number, including zero as inputs, no further testing will be needed.

1 Like

Thanks! Jeez this is a great help!

could you show how this would be used in my code?

Write the functions at the top of your code, then follow that with the three input lines, then print the result.

def numeric_input(arg):
    # code from above

def operate(a, b, f):
    # code like above

first_num = numeric_input('first')
second_num = numeric_input('second')
operation = raw_input("Enter 'add' or 'subtract' as operation.")

print (operate(first_num, second_num, operation))

This is a basic working program. It can be extended very easily to include multiplication, division, modulo, square root, etc. just by adding new cases to the switch and writing the applicable return statement.

The input segment (the last four lines above) could be wrapped in a loop so the program is always waiting for new input. Remember to include a way to exit the program. If you get stuck in a loop use Ctrl C to quit the interpreter, but that is not the ideal approach.

#I’ve got this but now it says invalid Syntax on line 11

print str("Hello and welcome to Alfie's calculator Alpha V1.0")

def numeric_input(arg):
    while True:
        try:
            return int(raw_input("Enter your %s operand:" % arg))
        except ValueError:
            print "Value Error: try again"

def operate(a, b, f):
    function operate(a, b, f) {
switch (f) {
case 'add': return a + b;
case 'subtract': return a - b;
default: return "error: wrong operation input"
}
}

print (operate(first_num, second_num, operation))

first_num = numeric_input('first')
second_num = numeric_input('second')
operation = raw_input("Enter 'add' or 'subtract' as operation.")

print (operate(first_num, second_num, operation))`Preformatted text`

I have really messed up. My mind is in too many places at once, it would seem. Python doesn’t have a switch statement. Must be right off my head. My apologies. Which language should we be working with, JavaScript or Python?

Here is a substitute for the switch in Python,

def operate(a,b,f):
    cases = {
        'add': lambda a, b: a + b,
        'subtract': lambda a, b: a - b
    }
    try:
        return cases[f](a,b)
    except KeyError:
        return "Key Error: try again"
>>> operate(5,7,'add')
12
>>> operate(1,2,"")
'Key Error: try again'
>>> 

Here is the proof of concept in Python:

def operate(a,b,f):
    cases = {
        'add': lambda a, b: a + b,
        'subtract': lambda a, b: a - b
    }
    try:
        return cases[f](a, b)
    except KeyError:
        return "Key Error: try again"

def numeric_input(arg):
    while True:
        try:
            return float(raw_input("Enter your %s operand: " % arg))
        except ValueError:
            print ("Value Error: try again")

first_num = numeric_input('first')
second_num = numeric_input('second')
operation = raw_input("Enter 'add' or 'subtract' as operation: ")

print (operate(first_num, second_num, operation))
Enter your first operand: 32
Enter your second operand: 56
Enter 'add' or 'subtract' as operation: add
88.0

Enter your first operand: 45.6
Enter your second operand: 68.9
Enter 'add' or 'subtract' as operation: add
114.5
1 Like

thankyou!!:grinning:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.