Question

In: Computer Science

Python programming: can someone please fix my code to get it to work correctly? The program...

Python programming: can someone please fix my code to get it to work correctly? The program should print "car already started" if you try to start the car twice. And, should print "Car is already stopped" if you try to stop the car twice. Please add comments to explain why my code isn't working. Thanks!

# Program goals:
# To simulate a car game. Focus is to build the engine for this game.
# When we run the program, it should display: ">" , then the terminal waits for user input
# If we type "help", the terminal will list the commands that our program/game currently supports
#   start - to start the car
#   stop - to stop the car
#   quit - to terminate the game
# If we type anything other than the currently supported commands,
#   then the program should display: "Sorry, I don't understand."
# If we type start, then display: "Car started... ready to go!"
#   If we type start while car is already started, then display: "Car already started."
# If we type stop, then display: "Car stopped."
#   If we type stop, when car is already stopped, display: "Car already stopped."
# If we type quit, then terminate the game.


# my attempt for this program:
print("This program simulates a car game.")
print('Type "help" to display a list of working commands.')

help = '''
List of working commands:
    "start": start the car
    "stop": stops the car
    "quit": terminates the game
'''

command = ""  #initializes as an empty str variable
started = False  #initialize started to False

while True:  #means the following block of code in the while loop will be executed till it reaches 'break' function
    command = input("> ").lower()  #.lower method will lowercase any and every letters inputted by user
    if command == "start":
        if started:
            print("Car already started.")
        else:
            print("Car started... ready to go!")
            started == True
    elif command == "stop":
        if not started:  # implies if car is stopped
            print("Car already stopped!")
        else:
            print("Car has now stopped.")
            started == False
    elif command == "help":
        print(help)
    elif command == "quit":
        print("Game terminated.")
        break
    else:
        print("Sorry, I don't understand that. Please enter a working command.")

Solutions

Expert Solution

NOTE -

There was a little mistake in your program which was the reason that was stopping your program from working properly.

While trying to assign True to started in the else part of the start command you used "==" instead of "=". Same thing is repeated when you are trying to assign False to started in the else part of the stop command. "==" is a comparison operator and cannot be used for assigning. "=" is the assignment operator that can be used while assigning a value to a variable.

I have modified the code accordingly and also attached a screenshot with the code.

CODE -

print("This program simulates a car game.")
print('Type "help" to display a list of working commands.')

help = '''
List of working commands:
"start": start the car
"stop": stops the car
"quit": terminates the game
'''

command = "" #initializes as an empty str variable
started = False #initialize started to False
while True: #means the following block of code in the while loop will be executed till it reaches 'break' function
command = input("> ").lower() #.lower method will lowercase any and every letters inputted by user
if command == "start":
if started:
print("Car already started.")
else:
print("Car started... ready to go!")
started = True
elif command == "stop":
if not started: # implies if car is stopped
print("Car already stopped!")
else:
print("Car has now stopped.")
started = False
elif command == "help":
print(help)
elif command == "quit":
print("Game terminated.")
break
else:
print("Sorry, I don't understand that. Please enter a working command.")

SCREENSHOT -

If you have any doubt regarding the solution, then do comment.
Do upvote.


Related Solutions

Please add to this Python, Guess My Number Program. Add code to the program to make...
Please add to this Python, Guess My Number Program. Add code to the program to make it ask the user for his/her name and then greet that user by their name. Please add code comments throughout the rest of the program If possible or where you add in the code to make it ask the name and greet them before the program begins. import random def menu(): print("\n\n1. You guess the number\n2. You type a number and see if the...
I am getting 7 errors can someone fix and explain what I did wrong. My code...
I am getting 7 errors can someone fix and explain what I did wrong. My code is at the bottom. Welcome to the DeVry Bank Automated Teller Machine Check balance Make withdrawal Make deposit View account information View statement View bank information Exit          The result of choosing #1 will be the following:           Current balance is: $2439.45     The result of choosing #2 will be the following:           How much would you like to withdraw? $200.50      The...
Please fix all of the errors in this Python Code. import math """ A collection of...
Please fix all of the errors in this Python Code. import math """ A collection of methods for dealing with triangles specified by the length of three sides (a, b, c) If the sides cannot form a triangle,then return None for the value """ ## @TODO - add the errlog method and use wolf fencing to identify the errors in this code def validate_triangle(sides): """ This method should return True if and only if the sides form a valid triangle...
Python 3 Fix the code so the program reads the file and see if the bar...
Python 3 Fix the code so the program reads the file and see if the bar code was already inputted 3 times if so, it ishows a warning indicating that the item was already tested 3 times Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window,...
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)
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class Main { static int comparisons; static int exchanges; // Recursive function to perform insertion sort on sub-array arr[i..n] public static void insertionSort(int[] arr, int i, int n) { int value = arr[i]; int j = i; // Find index j within the sorted subset arr[0..i-1] // where element arr[i] belongs while (j > 0 && arr[j - 1] > value) { arr[j] = arr[j...
can someone code this problem please? Introduction Students will create a C++ program that simulates a...
can someone code this problem please? Introduction Students will create a C++ program that simulates a Pokemon battle mainly with the usage of a while loop, classes, structs, functions, pass by reference and arrays. Students will be expected to create the player’s pokemon and enemy pokemon using object-oriented programming (OOP). Scenario You’ve been assigned the role of creating a Pokemon fight simulator between a player’s Pikachu and the enemy CPU’s Mewtwo. You need to create a simple Pokemon battle simulation...
can someone please check this code? – Enter Quantity of Numbers Design a program that allows...
can someone please check this code? – Enter Quantity of Numbers Design a program that allows a user to enter any quantity of numbers until a negative number is entered. Then display the highest number and the lowest number. For the programming problem, create the pseudocode and enter it below. Enter pseudocode here start     Declarations           num number           num high             num low              housekeeping()     while number >=0 detailLoop()      endwhile      finish() stop housekeeping( )           output...
Please fix this python code for me DOWN_PAYMENT_RATE = 0.10 ANNUAL_INTEREST_RATE = 0.12 MONTHLY_PAYMENTS_RATE = 0.05...
Please fix this python code for me DOWN_PAYMENT_RATE = 0.10 ANNUAL_INTEREST_RATE = 0.12 MONTHLY_PAYMENTS_RATE = 0.05 purchasePrice = float(input("Enter the purchase price: ")) month = 1 payment = purchasePrice * MONTHLY_PAYMENTS_RATE startingBalance = purchasePrice print("\n%s%19s%18s%19s%10s%17s" % ("Month", "Starting Balance", "Interest to Pay", "Principal to Pay", "Payment", "Ending Balance")) while startingBalance > 0:     interestToPay = startingBalance * ANNUAL_INTEREST_RATE / 12     principalToPay = payment - interestToPay     endingBalance = startingBalance - payment     print("%2d%16.2f%16.2f%18.2f%18.2f%15.2f" % (month, startingBalance, interestToPay, principalToPay, payment,...
(Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using...
(Full Program)Write code that shows how deadlocks work. Then write code that shows a fix using semaphores. (Full program)Write code showing the elevator algorithm. c++ Language
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT