Question

In: Computer Science

Could someone please tell me what corrections I should make to this code. (Python) Here are...

Could someone please tell me what corrections I should make to this code. (Python)

Here are the instructions.

  • Modify the program so it contains four columns: name, year, price and rating (G,PG,R…)
  • Enhance the program so it provides a find by rating function that lists all of the movies that have a specified rating

I can't get the find function to work and I have no idea how to even go about it. For example, when type in 'find' and I enter the rating, I'm always getting an error. I need help.


def list(movie_list):
if len(movie_list) == 0:
print("There are no movies in the list.\n")
return
else:
i = 1
for row in movie_list:
print(str(i) + ". " + row[0]+ " (" + str(row[1]) + ")"+","+ "$"+str(row[2])+","+str(row[3]))
i += 1
print()

def add(movie_list):
name = input("Name: ")
year = input("Year: ")
price = int(input("Price:"))#price
rating =input("Rating:")
movie = []
movie.append(name)
movie.append(year)
movie.append(price)#adding price to the movie list
movie.append(rating)#adding rating to the movie list
movie_list.append(movie)
rating_list.append(movie)
print(movie[0] + " was added.\n")   

def delete(movie_list):
number = int(input("Number: "))
if number < 1 or number > len(movie_list):
print("Invalid movie number.\n")
else:
movie = movie_list.pop(number-1)
print(movie[0] + " was deleted.\n")
#find by rating function
def find_by_rating(movie_list,rating):
if len(movie_list)==0:
print("Find")
return
else:
movie_list=[]
for i in movie_list:
if i[3]==rating:
movie_list.append(i[0])
if len(1)==0:
print("No movies are present with given rating")
else:
print("Movies:")
for i in movie_list:
print(i)
  
  
def display_menu():
print("COMMAND MENU")
print("list - List all movies")
print("add - Add a movie")
print("del - Delete a movie")
print("find- find movie by rating")
print("exit - Exit program")
print()

def main():
movie_list = [["Matrix",1999,9.75,"R"],
["Under the Tuscan",2003,4.99,"PG"],
["V for Vendetta", 2005,14.99,"R"]]

display_menu()
  
while True:
command = input("Command: ")
if command == "list":
list(movie_list)
elif command == "add":
add(movie_list)
elif command == "del":
delete(movie_list)
elif command == "find": #added find command
rating=input("Enter rating:")#taking the rating
find_by_rating(movie_list,rating)#the call
elif command == "exit":
break
else:
print("Not a valid command. Please try again.\n")
print("Bye!")

if __name__ == "__main__":
main()

Solutions

Expert Solution

Here is the code in python for the given problem.

Some corrections are done to the code provided in the question so that the program works as expected.

Some comments are added to the find() function (asked in the question) for better understanding.

Sample output is added at the end.

Code:

def list_movies(movie_list):
    if len(movie_list) == 0:
        print("There are no movies in the list.\n")
        return
    else:
        i = 1
        for row in movie_list:
            print(str(i) + ". " + row[0]+ " (" + str(row[1]) + ")"+","+ "$"+str(row[2])+","+str(row[3]))
            i += 1
            print()

def add(movie_list):
    name = input("Name: ")
    year = input("Year: ")
    price = float(input("Price:"))#price
    rating =input("Rating:")
    movie = []
    movie.append(name)
    movie.append(year)
    movie.append(price)#adding price to the movie list
    movie.append(rating)#adding rating to the movie list
    movie_list.append(movie)
    print(movie[0] + " was added.\n")   

def delete(movie_list):
    number = int(input("Number: "))
    if number < 1 or number > len(movie_list):
        print("Invalid movie number.\n")
    else:
        movie = movie_list.pop(number-1)
        print(movie[0] + " was deleted.\n")
        
#find by rating function
def find_by_rating(movie_list,rating):
    if len(movie_list)==0:           #checks if movie_list is empty
        print("There are no movies in the list")
        return
    else:
        movie_list_by_rating=[]      #creates a new list
        for i in movie_list:
            if i[3]==rating:      #checks if the current movie rating is equal to the rating passed as parameter
               movie_list_by_rating.append(i[0])    #append movie to movie_list_by_rating list
        if len(movie_list_by_rating)==0:    #checks if movie_list_by_rating is empty   
            print("No movies are present with given rating")
        else:
            print("Movies:")
            for i in movie_list_by_rating:
                print(i)              #prints movies with rating passed as parameter
  
  
def display_menu():
    print("COMMAND MENU")
    print("list - List all movies")
    print("add - Add a movie")
    print("del - Delete a movie")
    print("find- find movie by rating")
    print("exit - Exit program")
    print()

def main():
    movie_list = [["Matrix",1999,9.75,"R"],
            ["Under the Tuscan",2003,4.99,"PG"],
                ["V for Vendetta", 2005,14.99,"R"]]

    display_menu()
  
    while True:
        command = input("Command: ")
        if command == "list":
            list_movies(movie_list)
        elif command == "add":
            add(movie_list)
        elif command == "del":
            delete(movie_list)
        elif command == "find": #added find command
            rating=input("Enter rating:")#taking the rating
            find_by_rating(movie_list,rating)#the call
        elif command == "exit":
            break
        else:
            print("Not a valid command. Please try again.\n")
    print("Bye!")

if __name__ == "__main__":
    main()

Sample output:


Related Solutions

I need to fix this code, and could you please tell me what was the problem...
I need to fix this code, and could you please tell me what was the problem options 1 and 9 don't work #include <stdio.h> #include <time.h> #include <stdlib.h> // generate a random integer between lower and upper values int GenerateRandomInt(int lower, int upper){     int num =(rand()% (upper - lower+1))+lower;     return num; } // use random numbers to set the values of the matrix void InitializeMatrix(int row, int column, int dimension, int mat[][dimension]){     for(int i =0; i<row; i++){...
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------...
I was wondering is someone could tell me why my code isn't compiling - Java ------------------------------------------------------------------------------------------------------------ class Robot{ int serialNumber; boolean flies,autonomous,teleoperated; public void setCapabilities(int serialNumber, boolean flies, boolean autonomous, boolean teleoperated){ this.serialNumber = serialNumber; this.flies = flies; this.autonomous = autonomous; this.teleoperated = teleoperated; } public int getSerialNumber(){ return this.serialNumber; } public boolean canFly(){ return this.flies; } public boolean isAutonomous(){ return this.autonomous; } public boolean isTeleoperated(){ return this.teleoperated; } public String getCapabilities(){ StringBuilder str = new StringBuilder(); if(this.flies){str.append("canFly");str.append(" ");} if(this.autonomous){str.append("autonomous");str.append("...
Okay, can someone please tell me what I am doing wrong?? I will show the code...
Okay, can someone please tell me what I am doing wrong?? I will show the code I submitted for the assignment. However, according to my instructor I did it incorrectly but I am not understanding why. I will show the instructor's comment after providing my original code for the assignment. Thank you in advance. * * * * * HourlyTest Class * * * * * import java.util.Scanner; public class HourlyTest {    public static void main(String[] args)     {        ...
Can someone tell me what is wrong with this code? Python pong game using graphics.py When...
Can someone tell me what is wrong with this code? Python pong game using graphics.py When the ball moves the paddles don't move and when the paddles move the ball doesn't move. from graphics import * import time, random def racket1_up(racket1):    racket1.move(0,20)        def racket1_down(racket1):    racket1.move(0,-20)   def racket2_up(racket2):    racket2.move(0,20)   def racket2_down(racket2):    racket2.move(0,-20)   def bounceInBox(shape, dx, dy, xLow, xHigh, yLow, yHigh):     delay = .005     for i in range(600):         shape.move(dx, dy)         center = shape.getCenter()         x = center.getX()         y = center.getY()         if x...
Can anyone please tell me what function in excel I could use in this instance: I...
Can anyone please tell me what function in excel I could use in this instance: I have two spreadsheets with sales of products for a company. I am needing to create a new spreadsheet with gross sales by month and by region. It haven't included all the worksheets, because I truly just need pointed in the right direction.
I kept getting errors trying to make this code to work, can someone show me what...
I kept getting errors trying to make this code to work, can someone show me what i am doing wrong? import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.*; import java.util.*; import java.nio.file.*; import java.nio.charset.*; import java.util.*; //@WebServlet(name = "Assignment3_1", urlPatterns = { "/ReadFile" }) public class ReadFile extends HttpServlet{ static Charset myCharset = Charset.forName("US-ASCII"); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/html"); PrintWriter printer = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>"); out.println("Assignment 5.1"); out.println("</title>"); out.println("<h1>Is Bitcoin money?</h1>"); out.println("</head>"); out.println("<body>");...
Can someone please explain to me why "return 1" in this Python code returns the factorial...
Can someone please explain to me why "return 1" in this Python code returns the factorial of a given number? I understand recursion, but I do not understand why factorial(5) returns 120 when it clearly says to return 1. def factorial(n): if n == 0: return 1 else: return n * factorial(n-1)
Could you please tell me what it is?use what theroy? Rather than exporting or FDI I...
Could you please tell me what it is?use what theroy? Rather than exporting or FDI I can negotiate a contract that gives another company the right to make my product in their country.This is known as: When an immigrant sends money to his or her family back in their home country. (it’s difficult to measure) When more expensive goods sourced from inside a customs union replace the consumption of less expensive goods from outside the customs union. A situation in...
Can someone please tell me on how can I have a double and character as one...
Can someone please tell me on how can I have a double and character as one of the items on my list? Thanks! This is what I got so far and the values I am getting are all integers. #pragma once #include <iostream> class Node { public:    int data;    Node* next;       // self-referential    Node()    {        data = 0;        next = nullptr;    }    Node(int value)    {        data...
Can someone please tell me why I am getting errors. I declared the map and it's...
Can someone please tell me why I am getting errors. I declared the map and it's values like instructed but it's telling me I'm wrong. #include <iostream> #include <stdio.h> #include <time.h> #include <chrono> #include <string> #include <cctype> #include <set> #include <map> #include "d_state.h" using namespace std; int main() { string name; map<string,string> s; map<string,string>::iterator it; s[“Maryland”] = "Salisbury"; s[“Arizona”] = "Phoenix"; s[“Florida”] = "Orlando"; s[“Califonia”] = "Sacramento"; s[“Virginia”] = "Richmond"; cout << "Enter a state:" << endl; cin >> name;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT