-2

I just started learning python, while using the try command in exception handling, I got an syntax error

Here is my code,

def divide(a,b):
    {
        print(a," hello world", b)
        try:
            return a/b
        except:
            print("It is meaningless")
    }
print(divide(1,2))

Here is my output,

PS D:\python> python firstprog.py
  File "firstprog.py", line 4
    try:
      ^
SyntaxError: invalid syntax

Can you help me?

1 Answers1

-1

First remove your curly braces, curly braces in python are used for dictionaries/sets shorthand declaration.

like:

def divide(a,b):
    print(a," hello world", b)
    try:
        return a/b
    except:
        print("It is meaningless")

print(divide(1,2))

because with curly braces and a colon python is thinking it is some sort of dictionary and throwing an error near try.

Avezan
  • 673
  • 4
  • 9
  • Please avoid answering this kind of questions, it doesn't make sense i did the same thing, i answered the question but quickly deleted it because i realized that answering this kind of questions don't make sense – U13-Forward Jun 13 '18 at 02:55
  • Note that semicolon is allowed – U13-Forward Jun 13 '18 at 02:56
  • What kind of question are you expecting from a new comer. Not every one is so experienced to ask high level questions. In your experience this question is redundant, in mine the highest voted so question is headless because branch prediction is taught in CS 2nd year. – Avezan Jun 13 '18 at 02:58
  • Sorry i forgot to mention if there are this kind of questions write it in the comments, okay? – U13-Forward Jun 13 '18 at 02:59
  • I ellaborated on why curly braces will not work. if he had written like `def divide(a,b): {print('a'): print('b')}` the code would have run successfully – Avezan Jun 13 '18 at 03:01