lundi 18 octobre 2021

If an input interval is within another interval, append to list

I am writing a program that informs the user which animals will be awake and fed during their visit to the zoo, based on their inputs of day and time. I have a class, a function that reads a file with info including name, hours awake, at what time they'll be fed, and some other stuff that all works.

 class Animal:
      def __init__(self, name, sleep, diet, awake, feed, number):
           self.name = name
           self.sleep = sleep
           self.diet = diet
           self.awake = awake
           self.feed = feed
           self.number = number
      def __repr__(self):
           return self.name + " " + self.sleep + " " + self.diet + " " + str(self.awake) + " " + str(self.feed) + " " + str(self.number)

 def readInfo():
      infile = open("zoo.txt", "r", encoding="UTF-8")
      animals = []
      lines = infile.readlines()
      infile.close
      for line in lines:
           lineparts = line.split(" / ")
           name = lineparts[0]
           sleep = lineparts[1]
           diet = lineparts[2]
           awake = lineparts[3]
           feed = lineparts[4]
           number = lineparts[5]
           animals.append(Animal(name, sleep, diet, awake, feed, number))
      return animals

 def Awake(x):
      awakeanimals = x
      print("\nYou can see ")
      for object in awakeanimals:
           print(object)

 def Feed(x):
      matadjur = x
      print("\nand you can feed: ")
      for object in feedanimals:
           print(object)

Here is my code I'm struggling with:

def open():
     animals = readInfo()
     awake = list()
     feed = list()
     time = int(input("Enter a time interval, eg 07-16")).split("-")

     if 9 <= time <= 20:
          awakeanimals.append(animals[0].name)
     if 12 <= time <= 14:
          awakeanimals.append(animals[1].name)
     if 21 >= time >= 05:
          awakeanimals.append(animals[2].name)
     #same for the rest of the animals

     if time <= 12 <= time:
          feedanimals.append(animals[0].name)
     if time <= 13 <= time:
          feedanimals.append(animals[0].name)
     #same for the rest of the animals

Awake(awakeanimals)
Feed(feedanimals)

After that I have a simple menu which, based on the day the user inputs, calls the funciton open() and goes on to the time part.

I don't know how to get the correct input in the if conditions.

Also, the time = input().split("-") doesn't work due to ValueError: invalid literal for int() with base 10, so I'm thinking of using two time inputs, time1 = input(), and time2 = input(). However, that seems more complicated to incorporate in the if condition.

Aucun commentaire:

Enregistrer un commentaire