Question

I'm working on building a simple python program for a class which will run on a Raspberry Pi and an Arduino to direct a telescope. I had started to learn python some time ago, and I'm having trouble getting my functions to work properly. Right now, I have this:

import ephem

def const(p, d): # find the constellation #
    def loc():
        sbend = ephem.Observer()
        sbend.lat = '41.67'
        sbend.lon = '86.26'
        p = getattr(ephem, p)
        p.compute(sbend)
        print p.alt, p.az

    o = getattr(ephem, p)
    print ephem.constellation(o(d))
    return loc()

const(raw_input('Planet: '), raw_input('yyyy/mm/dd: '))

From what I remember, a function inside another can call a variable from the parent. Can it also work the other way round like I have at the end? I'd like to be able to print the constellation (which is working) as well as the alt and az of the planet based on the hardcoded location. For some reason, it isn't calculating the altitude and azimuth though. Thoughts?

EDIT

I added return loc() on line 14.

I was doing more reading and some other threads said that to get to an inner function, it needs to be returned at the end of the parent. But, it's still not working for me.

Was it helpful?

Solution

I am not clear on why you have one function inside of another, so I might be missing part of the problem that you are trying to solve; but if I wanted to determine in what constellation a planet lies, where the planet's name and the date are provided as inputs, then I would simply perform those steps all in a row, without any complicated functions-inside-of-functions:

import ephem

def const(planet_name, date_string):
    planet_class = getattr(ephem, planet_name)
    planet = planet_class()
    south_bend = ephem.Observer()
    south_bend.lat = '41.67'
    south_bend.lon = '-86.26'  # west is negative
    south_bend.date = date_string
    planet.compute(south_bend)
    return ephem.constellation((planet.ra, planet.dec))

print const(raw_input('Planet: '), raw_input('yyyy/mm/dd: '))

OTHER TIPS

Taking @Brandon's example, here is my final code:

import ephem

def const(planet_name, date_string): 
    planet_class = getattr(ephem, planet_name) 
    planet = planet_class() 
    south_bend = ephem.Observer()
    south_bend.lat = '41.67'
    south_bend.lon = '-86.26'
    south_bend.date = date_string              
    planet.compute(south_bend)                  
    print ephem.constellation((planet.ra, planet.dec))
    return planet.alt, planet.az

print const(raw_input('Planet: '), raw_input('yyyy/mm/dd: '))

I realized after looking at it that he was using planet.ra and planet.dec to locate the background constellation, not to print it's coordinates in the sky. All I did was add the return call at the end to print the altitude and azimuth data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top