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...
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...
I cannot get this code to run on my python compiler. It gives me an expected...
I cannot get this code to run on my python compiler. It gives me an expected an indent block message. I do not know what is going on. #ask why this is now happenning. (Create employee description) class employee: def__init__(self, name, employee_id, department, title): self.name = name self.employee_id = employee_id self.department = department self.title = title def __str__(self): return '{} , id={}, is in {} and is a {}.'.format(self.name, self.employee_id, self.department, self.title)    def main(): # Create employee list emp1...
Python 3 Fix the code so i can make the window larger or smaller and the...
Python 3 Fix the code so i can make the window larger or smaller and the fields adjusts everytime according to the window size import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # 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, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window)...
can you please create the code program in PYTHON for me. i want to create array...
can you please create the code program in PYTHON for me. i want to create array matrix Nx1 (N is multiple of 4 and start from 16), and matrix has the value of elements like this: if N = 16, matrix is [ 4 4 4 4 -4 -4 -4 -4 4 4 4 4 -4 -4 -4 -4] if N = 64, matrix is [8 8 8 8 8 8 8 8 -8 -8 -8 -8 -8 -8 -8...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT