Can somebody explain reason for occurring error of this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can somebody explain reason for occurring error of this code?

def calculate_area(): print(area) area=3.14*radius**2 print(area) radius=4 area=4 calculate_area()

11th Dec 2018, 2:58 PM
최호준
4 Answers
+ 6
at statement print(area) ( the first one )error occurs in function calculate_area() when it sees 1st print (area) it doesn't recognize it since your variable area is not defined in that function After you write area=..... Now your area is defined with some value now print will recognize it and print its value https://code.sololearn.com/cl57T03v799f/?ref=app
11th Dec 2018, 3:07 PM
Rstar
Rstar - avatar
+ 5
Try to understand the error. It's saying: local variable 'area' referenced before assignment and it's bcz the variable 'area' is local to that function and in there it can't find an assignment for 'area' prior to it's use in the print statement. Now if you want to use the global variable 'area=4' inside the function, you must add `global area` `global radius` in the function before using it. In this case, before that first print statement.
11th Dec 2018, 3:15 PM
Шащи Ранжан
Шащи Ранжан - avatar
+ 4
you have to declare the variables as global inside calculate_area() Find the code below: def calculate_area(): global area global radius print(area) area=3.14*radius**2 print(area) radius=4 area=4 calculate_area()
11th Dec 2018, 3:21 PM
Rishi Anand
Rishi Anand - avatar
+ 2
Thanks everyone. This is not in the tutorial.
11th Dec 2018, 3:54 PM
Genghis
Genghis - avatar