-2

Def, return

>>> def square(x):
    return x*x
print (square(4))
SyntaxError: invalid syntax
>>> 

Hi, can you help me out about this programming problem ? I used python 3.0 to write the code, but it seems like error . I have looked for the answer from several website that can’t solve the problem. Even I copied others code to write , it still , the error showed up ..

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • In Python, the way you indent your lines matters. The way you copied your code snippet doesn't really reflect what's on your screenshot. So I assume you've messed up your indentation. – Vym Sep 05 '21 at 10:51
  • 1
    You have pasted more than one statement (`def `and `print`) at the `>>>` prompt. IDLE doesn't accept that. Everything typed at the prompt must be a single statement or the beginning of one. Paste the function definition and the `print()` call in 2 separate steps. – BoarGules Sep 05 '21 at 11:12
  • If one enters the same 3 lines into standard interactive Python REPL, with the middle line indented, one gets the same error message. So this is not about IDLE at all. In 3.10+, IDLE's Shell keeps the code lines properly lined up, as in the REPL. I may or may not backport the change to 3.9. – Terry Jan Reedy Sep 06 '21 at 20:16

2 Answers2

1

So def works with similar formatting to if else's and for loops. This means your code should look something like

def square(x):
  return x*x
print(square(4)

Although you could cut out the function and just have

print(x^2)
kineticcat_
  • 117
  • 2
  • 9
  • _similar formatting_, you could simply say that function definition are supposed to indented. – PCM Sep 05 '21 at 10:58
0

Here is my example you can examine it:

def cal(x, y):
    return x+y
print(f"10 + 10 = {cal(10, 10)}")

And How To Use Parameters:

def cal(x,y, operation=None):
    opt = ['+', '-', '*', '/']
    if not operation in opt:
        raise TypeError("No Operation To Use")
    elif operation == opt[0]:
        # +
        return x+y
    elif operation == opt[1]:
        # -
        return x-y
    elif operation == opt[2]:
        # *
        return x*y
    elif operation == opt[3]:
        # /
        return x/y
    else:
        print(f"Operation {operation} is unkown")

call it using cal(10, 5, operation='+') or cal(10, 5, '+')

also it's better to use print("Hi") instead of print "Hi" or print ("Hi") because print is not a syntax

kielspiel
  • 61
  • 6