Search code examples
pythonraspberry-pisyntax-errorweather-api

IndexError: tuple index out of range in python by using Raspberry pi


Here is a code for calculating the radiation of the sun, but when I'm trying to run the code I get this error:

   Parsed config:  None
Traceback (most recent call last):
  File "/home/pi/SolarRadiationPlugin-master/run_plugin.py", line 13, in <module>
    print('Sunrise: {0}\r\nSunset: {1}'.format(solar_radiation.get_sunrise_sunset()))
IndexError: tuple index out of range

I'm not sure why this error is showing,

and here is the main code code :

https://github.com/UBayouski/SolarRadiationPlugin


Solution

  • solar_radiation.get_sunrise_sunset() returns a tuple of length 2. To use it with string formatting, you can unpack the tuple with *.

    print('Sunrise: {0}\r\nSunset: {1}'.format(*solar_radiation.get_sunrise_sunset()))
    

    In my opinion, you can improve readability by defining the values before the print.

    sunrise, sunset = solar_radiation.get_sunrise_sunset()
    print('Sunrise: {0}\r\nSunset: {1}'.format(sunrise, sunset))
    

    or with f-strings

    sunrise, sunset = solar_radiation.get_sunrise_sunset()
    print(f'Sunrise: {sunrise}\r\nSunset: {sunset}'