What I need help on is getting the stations to change to the next station in the list if the user presses 3.
class Radio:
def __init__(self):
self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
self.stationStart=self.stations[0]
def seekNext(self):
self.stationsStart
It starts at static but I want it to change every single one and then start over again. I tried something like this:
stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
a =input("enter 3 to seek next")
while a !="0":
if a =="3":
print(stations[-1])
I only end up getting the last station cannot figure out how to list the rest of the stations.
There are a couple of reasonable ways to do what you want.
The easiest would be to make your class store an index into your list, rather than an list item directly. That way you can increment the index and wrap it around using the %
modulus operator:
class Radio:
def __init__(self):
self.stations=["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"]
self.station_index = 0
def seek(self):
print("Currently tuned to", self.stations[self.station_index])
print("Seeking...")
self.station_index = (self.station_index + 1) % len(self.stations)
print("Now tuned to", self.stations[self.station_index])
A "fancier", and possibly more Pythonic way to solve the problem would be to use the cycle
generator from the itertools
module in the Python standard library. It returns an iterator that yields the values from your list, starting over when it reaches the end. Though you usually only deal with iterators in for
loops, it's easy to use the iterator protocol by hand too. In our case, we just want to call next
on the iterator to get the next value:
import itertools
class Radio:
def __init__(self):
self.stations = itertools.cycle(["STATIC","97.2", "99.6", "101.7", "105.3", "108.5"])
self.current_station = next(self.stations)
def seek(self):
print("Currently tuned to", self.current_station)
print("Seeking...")
self.current_station = next(self.stations)
print("Now tuned to", self.current_station)