Python Forum

Full Version: Understanding a piece of code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
def area(x,y = 3.14): # formal parameters
    a = y*x*x
    print (a)
    return a

a = area(10)
print("area",a)
* Here is what I am doing:
3.14 * 3.14 * 3.14 = 30.56476
30.56476 is a
then 30.56476 * 10
305.6476

but the actual answer is: 314.0 ( when you run the program)
Actually you are doing 10 * 3.14* 3.14 and the answer should be 98.596.

This is bad code. What does it do? area? area of what? By looking at the code I can see that this is the area of a circle with radius x, but I should not have to read the code. And why is y a variable? If this computes the area of a circle is y ever going to be something other than PI?
def circle_area(radius):
    """Returns area of circle with radius 'radius'"""
    return 3.14 * radius * radius
What is 3.14? It is kind of close to PI. If it is supposed to be PI, why not use PI?
import math

def circle_area(radius):
    """Returns area of circle with radius 'radius'"""
    return math.pi * radius**2
Im trying to understand why the complier gives 314.0
My mistake. Actually it is returning 3.14 * 10 * 10. I mixed up the x and y. That is a pretty good indication that x and y are not good variable names. They got me so confused I forgot how to calculate the area of a circle. And now my humiliation is frozen in time in Michael1's reply for all to see.

This is a better way to write the function in question. x should be renamed radius and y should be the constant pi, not a function argument. The function name should clearly indicate what the function does, and the function should have a docstring.
import math

def circle_area(radius):
    """Returns area of circle with radius 'radius' """
    return math.pi * radius**2
Thanks!