1--when we enter help following should appear:
start-to start the car
stop-to stop the car
quit-to exit
2--when we enter started message : car started should be shown
3--when entered stop: Car stopped should be displayed
4--when entered quit...should be exited through the loop
5--we cannot start car two times or more --message like car started already should be shown same with the stop
my code:
command=""
while True:
command=input('>').lower()
if command=='start':
print("Car started")
elif command=='stop':
print("Car stopped")
elif command=="help":
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
elif command=='quit':
break
else:
print("I don't understand that")
I did these part but was unable to prevent the car from starting twice. Help :)
You can use a simple flag is_car_started to record the status of whether the car is already started or not. When you start the car, set is_car_started to True. When you stop the car, set it to false.
command=""
is_car_started = False
while True:
command=input('>').lower()
if command=='start':
if is_car_started == True:
print("Car started already")
else:
is_car_started = True
print("Car started")
elif command=='stop':
is_car_started = False
print("Car stopped")
elif command=="help":
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
elif command=='quit':
break
else:
print("I don't understand that")
you can define a boolean variable outside your while loop. Like first_start = true.
Then inside your while loop in the if statement where you check if command=="start" you can set first_start to false.
On the very top you can add an if-statement that prints your message when first_start == false.
The if-statement would look something like this:if not first_start:...
You need to keep track of whether or not the car is started. You can also achieve a superior structure to your code with match/case (requires Python 3.10). For example:
started = False
while True:
match input('Enter command: ').lower():
case 'start':
if started:
print('Already started')
else:
print('Car started')
started = True
case 'stop':
if started:
print('Car stopped')
started = False
else:
print('Car not started')
case 'quit':
print('Goodbye')
break
case 'help':
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
case _:
print("I don't understand that")
i had a similar issue and this is how i resolved it
hope it helps...
if is_car_started == True:
print("car started already...")
else:
is_car_started = True
print("car started... ready to go")
Related
def timer():
for t in reversed(range(1, 11)):
sleep(1)
print(t)
if foundAllLetters == True:
break
if remaining_attempts == 0:
break
if t == 1:
sleep(1)
print('TIMES UP!')
t1 = Thread(target=timer)
t1.start()
while True:
displayBoard(hang, missedLetters, correctLetters, secretWord)
guess = getGuess(missedLetters + correctLetters)
A short context is I am coding a hangman game. What is going my way is that the timer and loop occurs simultaneously. What is not going my way is that I'm unable to stop the loop and restart the game once the timer is up. gameIsDone = True <- will restart my hangman game. I can't identify what variable to use with it.
I have tried to put gameIsDone = True right under print('TIMES UP!') but nothing happened. I have also tried and added t = 1 in my while loop under else statement, nothing happened.
I am new to python but might have accidentally picked an intermediate activity for my project :\
I am building a small car simulator game. it's like a terminal window, I type start and it started normally. I press stop and it stops. Unfortunately, when I start it again, I had a error like this.
Traceback (most recent call last):
File "C:\Users\****\OneDrive\New folder\Car Emulator.py", line 12, in <module>
turtle.shape('square')
File "<string>", line 5, in shape
turtle.Terminator
I don't know what does this mean, because I called the turtle.bye() function. Although I Searched all the Stack Overflow forums just like that. the code is like this:
while True:
command = input(">").lower()
if command == "start":
if engine == False:
engine = True
print("Car started.")
t.shape('square')
else:
restart = input("Car already started. Restart? (Y) Yes (N) No ")
if restart.upper == "Y":
engine = False
t.bye()
engine = True
t.shape('turtle')
print("Car Restarted.")
elif command == "stop":
if engine == True:
engine = False
t.bye()
print("Car stopped.")
else:
print("Car already stopped.")
elif command == "help":
print('''
start - start the car
stop - stop the car
quit - exit
''')
elif command == "quit":
please someone explain this to me
while True:
command = input(">").lower()
if command == "start":
if engine == False:
engine = True
print("Car started.")
#t.shape('square')
else:
restart = input("Car already started. Restart? (Y) Yes (N) No ")
if restart.upper == "Y":
engine = False
# t.bye()
engine = True
#t.shape('turtle')
print("Car Restarted.")
elif command == "stop":
if engine == True:
engine = False
#t.bye()
print("Car stopped.")
else:
print("Car already stopped.")
elif command == "help":
print('''
start - start the car
stop - stop the car
quit - exit
''')
elif command == "quit":
output
[root#localhost ~]# python3 test.py
>start
Car started.
>stop
Car stopped.
>start
Car started.
>stop
Car stopped.
>stop
Car already stopped.
>start
Car started.
>start
Car already started. Restart? (Y) Yes (N)
Check your while loop, if you want to repeat anything inside the while loop, it should have a correct indentation.
Example https://www.w3schools.com/python/python_while_loops.asp
Note: Removed some part of the code to test it.
command = input("> ")
started = False
while True:
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
it renders "car has already started" infinite time when i state "start" and likewise with other inputs. how do i inhibit this? would be very helpful if you explain it in beginner terms, thank you!!
You need to put the command inside the while loop, so that the loop stops until the user has enterd his desired command:
started = False
while True:
command = input("> ")
if command == "start":
...
Male sure to add the input to thie while loop. In your case, it is just taking one input and then the value of command is fixed. So, it is an infinite loop.
But when you change the location and keep it inside the loop, every time it asks for the input, the value of command will change.
Also, .lower() will convert the input to lower case to remove case insensitivity
started = False
while True:
command=input('>> ').lower()
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
You need input a new command every while loop, otherwise it will fall into infinite loop with the same first inputed command condiction.
code:
started = False
while True:
command = input("> ")
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
result:
> start
car started
> stop
car is stopped
> stop
car has already stopped
> start
car started
> start
car has already started
> quit
What is happening in your loop is:
while True - A while loop will always run until this statement is False, as True is never False, this will loop forever until the break command is ran.
if command == "start" - Because command is set outside of the while loop, it is always equal to start and this if statement will always run
The first run, it will print "car started" and every other loop after will print "car has already started".
To stop this, you need to change the value of command to change the behaviour each time you loop. To do this, you can just get an input at the start of the loop:
started = False
while True:
command = input("> ") # Input inside the loop
if command == "start":
if started:
print("car has already started")
else:
started = True
print("car started")
elif command == "stop":
if not started:
print("car has already stopped")
else:
started = False
print("car is stopped")
elif command == "quit":
break
You are never changing the value for command and the loop is running "while True", so it will never stop.
When the user gives the input, lets say "start", your script is assigning the string "start" to the command.
It is looping infinitely because the first if statement is checking the value for the variable command, which after the input will always be "start".
You can solve it in multiple ways.
One is to change the name of the variable after the if statement:
command = input("> ")
started = False
while True:
if command == "start":
if started:
print("car has already started")
command = ""
Another way is to add break commands after each if comparison.
You can also change while True to while not started. The loop will continue until you change the variable started to True, which you are already doing after each conditional block.
I'm programming a simple text adventure game with Python 3 and the cmd module.
I need to somehow trigger the game over method but I didn't find a solution on document.
The CMD module got the do_quit() function, but that needs user input, and quit() or exit() kills the whole program, whereas I just need to get out of cmdloop()
Any idea how to deal with this?
Thanks in advance!
def moveDirection(direction):
global location
if direction in rooms[location]:
if rooms[rooms[location][direction]].get(UNLOCKED, True) == True:
print('You move to the %s.' % direction)
location = rooms[location][direction]
if location == 'Hallway' and bGuardAlive == True:
print("Game over! Guard caught you!")
printLocation(location)
else:
print("Door is locked")
else:
print('You cannot move in that direction')
def main():
printLocation(location)
GameLoop().cmdloop()
class GameLoop(cmd.Cmd):
prompt = '\n> '
def do_quit(self, arg):
"""Quit the game."""
return True
Usually (if I understand correctly), you create you own class derived from Exception, you throw the exception at the place you want to exit, and you will have a try clause where you want to land.
After trial and error i get it working. I needed use postcmd()
Here is my code:
def postcmd(self, stop, line):
if bGuardAlive == False and location == 'Hallway':
print("Game over! Guard caught you!")
return True
elif location == 'Tower Ruins':
print("You won!")
return True
return stop
Hopefully this will help somebody
I'm trying to design a control interface for my system which sends and receives some data through serial link. My searches related to GUI design took me to understand the "multi-threading" issue and code below shows the latest position I arrived.
This indicates similar parts (e.g try, run) with the ones I've seen on example GUIs. I planned to convert this to a GUI, once I understand how it exactly works.
So the problem is after I start, stop the code below I can't restart it again. Because, as I understand, multi-threading features only one cycle: start, stop and quit. I mean it doesn't accept start command after stop.
My question is how I can make this code to accept start after stopping?
Best wishes
import threading, random, time
class process(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.leave = 0
print("\n it's running ...\n\n")
while self.leave != 1:
print "Done!"
time.sleep(1)
operate = process()
while True:
inputt = input(" START : 1 \n STOP\t : 0 \n QUIT\t : 2 \n")
try:
if int(inputt) == 1:
operate.start()
elif int(inputt) == 0:
operate.leave = 1
elif int(inputt) == 2:
break
except:
print(" Wrong input, try egain...\n")
Create process inside while True loop
if int(inputt) == 1:
operate = process()
operate.start()
It should work.
... but your code may need other changes to make it safer - you will have to check if process exists before you try to stop it. You could use operate = None to control it.
import threading
import random
import time
class Process(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.leave = False
print("\n it's running ...\n\n")
while self.leave == False:
print("Done!")
time.sleep(1)
operate = None
while True:
inputt = input(" START : 1 \n STOP\t : 0 \n QUIT\t : 2 \n")
try:
if int(inputt) == 1:
if operate is None:
operate = Process()
operate.start()
elif int(inputt) == 0:
if operate is not None:
operate.leave = True
operate.join() # wait on process end
operate = None
elif int(inputt) == 2:
if operate is not None:
operate.leave = True
operate.join() # wait on process end
break
except:
print(" Wrong input, try egain...\n")
Other method is not to leave run() when you set leave = True but keep running thead. You would need two loops.
def run(self):
self.leave = False
self.stoped = False
print("\n it's running ...\n\n")
while self.leave == False:
while self.stoped == False:
print("Done!")
time.sleep(1)