+ 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()
4 Antworten
+ 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
+ 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.
+ 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()
+ 2
Thanks everyone. This is not in the tutorial.