Why try doesn't work?? Need help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 2
23rd May 2020, 5:40 AM
ashu pandey
ashu pandey - avatar
6 Answers
+ 9
This might help support what ~ swim ~ has clearly stated a couple of times already. Near the end of section 8.4 of this link https://docs.python.org/3/reference/compound_stmts.html#the-try-statement ... it says: "When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’ The return value of a function is determined by the last return statement executed. Since the finally clause always executes, a return statement executed in the finally clause will always be the last one executed."
23rd May 2020, 6:31 AM
David Carroll
David Carroll - avatar
+ 1
David Carroll thanks, i really appreciate it i am just a beginner and trying to grasp the basics
23rd May 2020, 6:44 AM
ashu pandey
ashu pandey - avatar
0
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 You didn't put return in try so yeah both things will be printed but my code is different, and i wanna know how that works
23rd May 2020, 5:57 AM
ashu pandey
ashu pandey - avatar
- 1
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 So answer this def fun(): try: print("yo") return 0 finally: return 1 print(fun()) It's output is yo 1
23rd May 2020, 6:12 AM
ashu pandey
ashu pandey - avatar
- 1
𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 But after try the fun() function return giving return value 0 so how finally block is being executed yeah i think so finally runs even if function returns because the programmers wanted to clear the resources. Thanks
23rd May 2020, 6:16 AM
ashu pandey
ashu pandey - avatar
- 3
But if try runs it will return from the function
23rd May 2020, 5:53 AM
ashu pandey
ashu pandey - avatar