0

I am learning Python and am having an issue doing simple math...

def main():
    coneHeight = 4.5
    coneR = 1.5
    pi = 3.141

    cone = pi * (1/3) * coneHeight * (coneR * coneR)
    print cone

if  __name__ == '__main__':
    main()

If someone could tell me what I am doing wrong, that'd be great. Also, is the last line if __name__ needed? I have no idea what it does but I was it and it worked.

Xavier Barbosa
  • 3,919
  • 1
  • 20
  • 18
SDK4
  • 59
  • 1
  • 9

2 Answers2

2

The problem is that you are doing (1/3) which will evaluate to 0. This is because python's integer division (and in fact most programming languages' integer division) will truncate or round-down. Do this instead:

def main():
        coneHeight = 4.5
        coneR = 1.5
        pi = 3.141

        cone = pi * (1.0/3) * coneHeight * (coneR * coneR)
        print cone

if  __name__ =='__main__':main()

Or you could do:

from __future__ import division
def main():
    coneHeight = 4.5
    coneR = 1.5
    pi = 3.141

    cone = pi * (1/3) * coneHeight * (coneR * coneR)  #no need to do 1.0/3 anymore
    print cone

if  __name__ =='__main__':main()

As for your second question,

the __name__ variable is assigned the value '__main__' when the script is run directly (from the shell, cmd, bash, etc). Therefore, your script will only run when this .py file is run directly and main() will not be called if it is imported by another file.

Ruddy
  • 9,795
  • 5
  • 45
  • 66
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

Since you're new to python, if you are thinking in using it in future, read this first (spare some time): http://legacy.python.org/dev/peps/pep-0008/

Regarding your question, here's one solution (of many):

# https://docs.python.org/2/library/math.html
# no need to declare "pi", just use the tools already created
import math

def main():
  cone_height = 4.5
  cone_r = 1.5
  one_third = float(1) / 3

  cone = math.pi * one_third * cone_height * math.pow(cone_r, 2)
  print cone

if  __name__ == '__main__':
  main()
StefanNch
  • 2,569
  • 24
  • 31