-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 ..

3
  • 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. Commented Sep 5, 2021 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. Commented Sep 5, 2021 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. Commented Sep 6, 2021 at 20:16

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

similar formatting, you could simply say that function definition are supposed to indented.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.