Home > Mobile >  Input from user to print out a certain instance variable in python
Input from user to print out a certain instance variable in python

Time:12-03

I have created a class with programs:

class Program:
    def __init__(self,channel,start, end, name, viewers, percentage):
        self.channel = channel
        self.start = start
        self.end = end
        self.name = name
        self.viewers = viewers 
Channel 1, start:16.00 end:17.45 viewers: 100 name: Matinee:The kiss on the cross 
Channel 1, start:17.45 end:17.50 viewers: 45 name: The stock market today
Channel 2, start:16.45 end:17.50 viewers: 30 name: News
Channel 4, start:17.25 end:17.50 viewers: 10 name: Home building 
Channel 5, start:15.45 end:16.50 viewers: 28 name: Reality

I also have created a nested list with the programs:

[[1,16:00, 17,45, 100, 'Matinee: The kiss on the cross'],[1,17:45, 17,50, 45,'The stock market today'],[2,16:45, 17,50, 30,'News'], [4,17:25, 17,50, 10,'Home building'],[5,15:45, 16,50, 28,'Reality']

Now we want the user to be able to write the name of a program:

News

The result should be:

News 19.45-17.50 has 30 viewers

I thought about how you could incorporate a method to avoid the program from crashing if the input is invalid/ not an instance variable

I have tried this:


Check_input():
 print('Enter the name of the desired program:')
    
    while True:                               #Continue asking for valid input.
        try:
            name = input('>')
            if name == #is an instance?
                return name 
            else:
                print('Enter a program that is included in the schedule:')   #input out of range

        except ValueError:
            print('Write a word!')        #Word or letter as input
            print('Try again')

I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)

I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory"

Do you have any suggestions how to combat the problem?

All help is much appreciated!

CodePudding user response:

To avoid the program from crashing if the input is invalid, you can use a try-except block to catch any errors that may occur when the user inputs a program name that is not included in the list of programs. You can then use an if statement to check if the input is a valid program name, and if it is not, you can ask the user to input a different program name.

To access the correct program in the list of programs, you can use a for loop to iterate over the list and check if the user's input matches the name of any of the programs. If there is a match, you can access the information for that program and use it to print out the desired information.

class Program:
    def __init__(self,channel,start, end, name, viewers, percentage):
        self.channel = channel
        self.start = start
        self.end = end
        self.name = name
        self.viewers = viewers

programs = [
    {
        'channel': 1,
        'start': 16:00,
        'end': 17:45,
        'name': 'Matinee: The kiss on the cross',
        'viewers': 100
    },
    {
        'channel': 1,
        'start': 17:45,
        'end': 17:50,
        'name': 'The stock market today',
        'viewers': 45
    },
    {
        'channel': 2,
        'start': 16:45,
        'end': 17:50,
        'name': 'News',
        'viewers': 30
    },
    {
        'channel': 4,
        'start': 17:25,
        'end': 17:50,
        'name': 'Home building',
        'viewers': 10
    },
    {
        'channel': 5,
        'start': 15:45,
        'end': 16:50,
        'name': 'Reality',
        'viewers': 28
    }
]

def check_input():
    print('Enter the name of the desired program:')
    while True:
        name = input('>')
        if name in programs:
            return name
        else:
            print('Enter a program that is included in the schedule:')

program_name = check_input()

for program in programs:
    if program['name'] == program_name:
        print('{} {}-{} has {} viewers'.format(program_name, program['start'], program['end'], program['viewers']))

In this example, the programs list is a list of dictionaries, where each dictionary contains the information for a single program. The check_input function asks the user to input the name of a program, and checks if the input is a valid program name. If the input is valid, it returns the program name. The for loop then iterates over the list of programs and checks if the user's input matches the name of any of the programs. If there is a match, the program information is accessed and used to print out the desired information.

I hope this helps!

CodePudding user response:

I wonder if I should separate all the program-names from the nested list and check if the user enters a name in the list as input? (Maybe by creating a for-loop to iterate over?)

Well if all your programs have a unique name then the easiest approach would probably be to store them in a dictionary instead of a nested list like:

programs = {
    "News": Program("2", "16:45", "17:50", "News", "30", "60"),
    "Reality": <Initialize Program class object for this program>,
    ...
}

Then you could just use the get dictionary method (it allows you to return a specific value if the key does not exist) to see if the asked program exists:

name = input('>')     
program = programs.get(name, None)
if program:
    print(program)
else:
    # raise an exception or handle however you prefer

And if your programs don't have a unique name then you will have to iterate over the list. In which case I would probably return a list of all existing objects that have that name. A for loop would work just fine, but I would switch the nested list with a list of Program objects since you already have the class.

I also have a question regarding how to print out the selected program when the user enters the correct name? I understand how to rearrange them into the correct order to create the sentence. However, I don't know how to access the correct program in the "memory" Do you have any suggestions how to combat the problem.

I would say that the most elegant solution is to override the __str__ method of your Program class so that you can just call print(program) and write out the right output. For example:

class Program:
    def __init__(self,channel,start, end, name, viewers, percentage):
        self.channel = channel
        self.start = start
        self.end = end
        self.name = name
        self.viewers = viewers 
    
    def __str__(self):
        return self.name   " "   self.start   "-"   self.end   " has "   self.viewers   " viewers"

should print out

News 19.45-17.50 has 30 viewers

when you call it like:

program = programs.get(name, None)
if program:
    print(program)
  • Related