0

i have file name circle.py with code

import math


def circle_area(r):
    return math.pi * (r ** 2)


radii = [1, 0, 2 + 5j, -1, True, 'radius']
str = 'area of circle with radius = {radius} is area = {area}'
for r in radii:
    a = circle_area(r)
    print(str.format(radius=r, area=a))

and another file name cal.py with code:

from circles import circle_area

circle_area(2)

but instead of just running the circle_area function from circle it is running whole file which is resulting an error becuase there i am trying to find area using string instead of int

how can i just use this function and not run whole code there is no problem with indentation i have written and run the code from scratch in two different laptop but still getting the same error

Mohammad Yunus
  • 204
  • 1
  • 9
  • You need to put your code into functions/classes or define an entry point into the script i.e `if __name__ == "__main__":` – Sayse Sep 17 '20 at 11:02

2 Answers2

3

This is what the if __name__ == '__main__': guard is for. It prevents code in the file from running when it's not the main script:

import math

def circle_area(r):
    return math.pi * (r ** 2)

if __name__ == '__main__':
    # Nothing in this block runs on import, only if this is run as the main script
    radii = [1, 0, 2 + 5j, -1, True, 'radius']
    fmt = 'area of circle with radius = {radius} is area = {area}'
    for r in radii:
        a = circle_area(r)
        print(fmt.format(radius=r, area=a))

Note that I also changed str to fmt, because name-shadowing the built-in str constructor is asking for trouble.

The above is the minimalist change; in real code it's usually best to shove all of the "main" code into a function, which you invoke in the guard:

import math

def circle_area(r):
    return math.pi * (r ** 2)

def main():
    # Nothing in this block runs on import, only if this is run as the main script
    radii = [1, 0, 2 + 5j, -1, True, 'radius']
    fmt = 'area of circle with radius = {radius} is area = {area}'
    for r in radii:
        a = circle_area(r)
        print(fmt.format(radius=r, area=a))

if __name__ == '__main__':
    main()

This puts all the main variables into function scope, rather than global scope, which:

  1. Ensures utility functions in your module don't accidentally rely on globals only defined when it's run as a script
  2. Speeds up your code (reading/writing locals is faster than reading/writing globals)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

In circle.py, execute the code outside of the circle_area function in an if statement that checks if the calling module is the main module:

if __name__ == '__main__':
    radii = [1, 0, 2 + 5j, -1, True, 'radius']
    str = 'area of circle with radius = {radius} is area = {area}'
    for r in radii:
        a = circle_area(r)
        print(str.format(radius=r, area=a))
ApplePie
  • 8,814
  • 5
  • 39
  • 60