while True:
user_input = input('> ').lower()
if user_input == 'help':
print("""start - to start the car
stop - to stop the car
quit - to exit
""")
elif user_input == 'start':
print('car started...Ready to go!')
elif user_input == 'stop':
print('car stopped...')
elif user_input == 'quit':
break
else:
print('I donn\'t understand that')
So this is a simple program. However, the additional task was:
from the code above we can understand if the user entered "start" a message will be printed on the screen saying "car started" and if the user enters the same thing again, the same message will keep appearing. however, the task was if the user entered "start" the second time it should appear a different message, For example "the car is already started".
So only the first time it should show "car started" and rest of the times it should show "car is already started". the code below will show the answer but I cannot understand the logic behind it.
started = False
while True:
user_input = input('> ').lower()
if user_input == 'help':
print("""
start - to start the car
stop - to stop the car
quit - to exit
""")
elif user_input == 'start':
if started:
print("car is already started!")
else:
started = True
print('car started...')
elif user_input == 'stop':
if not started:
print("car is already stopped")
else:
started = False
print('car stopped...')
elif user_input == 'quit':
break
else:
print('I donn\'t understand that')
I do understand the while loop well but I don't understand the logic behind setting things to false and then true. How is the code being executed? How's the loop and if statements handling them?
code reference
https://www.youtube.com/watch?v=_uQrJ0TkZlc&ab_channel=ProgrammingwithMosh
while loops part
I try to go step by step, look at the comments.
''' Set the variable started to False, this will indicate if the car is started or not.
At the beginning it should be False, since we haven't started it. '''
started = False
''' While True means, we stuck inside this while loop FORVERER, so we will have to
'break' out of it using the break statement. '''
while True:
# Get the user input, and convert to lower case
user_input = input('> ').lower()
if user_input == 'help':
''' If user input was 'help', print the help, and then jump to the begining of the
while loop. '''
print("""
start - to start the car
stop - to stop the car
quit - to exit
""")
elif user_input == 'start':
''' If the input was 'start', we go into this branch '''
if started:
''' If started is True (note, initially it was false), we already started the car.
Just print, and start the loop again. '''
print("car is already started!")
else:
''' Else (started is False), we set it to True, indicating that we started the car,
and print that we started it. Then start the loop again. '''
started = True
print('car started...')
elif user_input == 'stop':
''' The input is 'stop', so we go into this branch '''
if not started: # Equivalent to 'if started == False'
''' We try to stop the car, but started is already false, so we can't stop twice. '''
print("car is already stopped")
else:
''' If started wasn't false, than it is true, and this is a logical crap.
BUT, we are here since started was True, so we set it to False, and print that
we stopped the car. '''
started = False
print('car stopped...')
elif user_input == 'quit':
''' User input was quit, so this is our exit point from this infinite 'while True' loop. '''
break
else:
''' We had no idea what was the input, print this message, and start the loop again. '''
print('I donn\'t understand that')
So Marz,
Your first program has only one set of check around user input ie if else works only based on user input. To take into consideration the state of car ie is it started or stopped we need another variable. So comes 'started' variable into picture. In your second program code the message is displayed checking both - user input and condition/state of car.
Hope that makes sense.
Related
I am a beginner in Python and was watching a 6 hr video by Mosh Hamedami.
He has shown an example of designing an elementary Car Game using a while loop.
The code is suggested is below:
command = ''
started = False
while command != 'quit':
command = input('Enter a Command: ').lower()
if command == 'start':
if started:
print("Car already Started! Let's go!")
else:
started = True
print("Car Started.... Ready to Go!!!")
elif command == 'stop':
if not started:
print('Car already stopped!')
else:
started = False
print('Car stopped!')
elif command == 'help':
print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
elif command == 'quit':
break
else:
print('Sorry, I do not understand that!')
The above program runs perfectly,
But if we exclude the elif command == 'quit' block of code from the above program,
and give the
User-input: 'quit'
the program returns the Output: Sorry, I do not understand that!
But according to my understanding of the while loop, when:
User-input: 'quit'
The while loop should stop getting executed since while condition becomes False.
Now, if while loop stops executing with user-input "quit" then how the else block defined within the while condition is getting executed?
A while loop does not terminate when the condition becomes false. It terminates when it evaluates the condition and the condition is found to be false. That evaluation doesn't happen until the beginning of each loop iteration, not immediately after some event occurs that will allow the condition to become false.
A better way to write this loop is to simply use True as the condition, as it doesn't require you to initialize command to a known non-terminating value, then let a break statement somewhere the loop terminate the command when appropriate.
started = False
while True:
command = input('Enter a Command: ').lower()
if command == 'quit':
break
if command == 'start':
if started:
print("Car already Started! Let's go!")
else:
started = True
print("Car Started.... Ready to Go!!!")
elif command == 'stop':
if not started:
print('Car already stopped!')
else:
started = False
print('Car stopped!')
elif command == 'help':
print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')
Of course, you don't need two separate if statements as I've shown here; you could combine them into one with if command == 'start' being the first elif clause of the combined if statement. But this provides an explicit boundary between "code that terminates the loop" and "code that allows the loop to continue".
The program actually stops when you type quit, but before stopping it prints "Sorry, I do not understand that!". You can fix this by putting command = input('Enter a Command: ').lower() before while and in the end of the while like this (so that while will check if command != quit immediately after inputing):
command = ''
started = False
command = input('Enter a Command: ').lower()
while command != 'quit':
if command == 'start':
if started:
print("Car already Started! Let's go!")
else:
started = True
print("Car Started.... Ready to Go!!!")
elif command == 'stop':
if not started:
print('Car already stopped!')
else:
started = False
print('Car stopped!')
elif command == 'help':
print(" 'start' - to start the car\n'stop' - to stop the car\n'quit' - to quit/close the game.")
else:
print('Sorry, I do not understand that!')
command = input('Enter a Command: ').lower()
Statement are executed sequentially.
The condition of the while statement is executed at the beginning of the loop while the "else:" is executed near the end. After the "input" is executed, the "else" near end of loop is executed first.
I want to ask a question about a boolean question inside the loop.
Let me first explain this:
if I Input help, then it will show me
start - to start the car,
stop - to stop the car,
quit- to exit,
If I Input start, stop, quit it will print above individually.
If I Input start and stop again it will show ("the car is already started") or ("the car is already stopped").
please see the code below:
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if started:
print("the car is already started")
else:
started = True
print("start the car")
elif command == "stop":
if not started:
print("the car is already stopped")
else:
started = False
print("stop the car")
elif command == "help":
print("""
start - to start the car
stop - to stop the car
quit- to exit
""")
elif command == "exit":
print("exit the game")
break
else:
print("don't understand")
My question is how do python find out if I already typed start or stop, which will print ("the car is already started") or ("the car is already stopped").
The boolean started which is defined as False at the beginning seems to be the answer in this loop, but I don't understand the logic behind this.
Thank you so much all for your help and support, really appreciate it.
I have written a piece of code with a while loop, that I want to run until the user enters the string exit. However, I don't want the loop to be stopped for a repeat prompt after every loop cycle. How can I achieve this?
Currently the code loops correctly, however it does not respond to exit once in the while loop.
if __name__ == '__main__':
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
while name == True:
if prog_question == "exit":
name = False
break
else:
temperature_info = measure_temp()
if temperature_info[1] == "No error":
if int(temperature_info[0]) < int(check_temp):
heater("on",check_period*60)
else:
heater("off",check_period*60)
else:
measure_temp()
You are trying to let the user interrupt an infinite loop.
Your idea using input has the disadvantage that the user needs to actually input something on each iteration.
It might be more interesting to use try/except for that:
from time import sleep
try:
print("Hit Ctrl-C to stop the program")
while True:
print("still running")
sleep(1)
except KeyboardInterrupt:
print("this is the end")
Or you could also have a look at the module signal.
Just move the prompt to inside of the loop.
name = True
while name:
prog_question = input("Enter exit to quit the heat tracker after a cycle.")
if prog_question == "exit":
name = False
break
else:
...
I am making a program through a tutorial video and the code is either starting, stopping or exiting a car. Part of the program is to make it so if the car is either already started, or already stopped, you tell them that in the program. My program will tell the user that the car is already started or stopped, but after I told it stop two times, and not just once.
Hopefully somebody could describe maybe the issue between the relationship of my while loop and the boolean inside my if statements?
action = ""
started = False
while action != 'exit':
action = input("Type either start, stop, exit to work this car: ").lower()
if action == "start":
if started:
print("The car is already started")
else:
started = True
print("Congrats you started the car! You can now either stop the car or exit the car!")
action == input("Type either stop or exit to work this car: ")
elif action == "stop":
if not started:
print("You already stopped the car")
else:
started = False
print("Congrats you stopped the car! You can now exit the car!")
action = input("Either start the car again or exit the car: ")
elif action == "exit":
print("Congrats you exited the car!")
break
else:
action = input("You typed an invalid response, type either start, stop or exit:")
pprint("The end")
Consider the case where the car has already been started, and the user has now entered 'stop'. That puts us in the else block here:
elif action == "stop":
if not started:
print("You already stopped the car")
else: # <-- here
started = False
print("Congrats you stopped the car! You can now exit the car!")
action = input("Either start the car again or exit the car: ")
The last line prompts the user to enter a new command, which resets action and brings you back to the top of the loop, where you immediately prompt the user for a new command:
action = input("Type either start, stop, exit to work this car: ").lower()
In other words, your code "forgets" what the user typed inside the 'stop' block, prompting them for a new command without processing the original entry.
You can resolve this pretty easily by moving the very first input line into one of the conditional blocks - the else. This has the added benefit of allowing you to keep the precision of prompting the user with the message that applies to their case (e.g. "Either start the car again or exit the car" when the user has just entered "stop"). Should look something like this:
action = ""
started = False
while True:
if action == "start":
if started:
print("The car is already started")
else:
started = True
print("Congrats you started the car! You can now either stop the car or exit the car!")
action = input("Type either stop or exit to work this car: ")
elif action == "stop":
if not started:
print("You already stopped the car")
else:
started = False
print("Congrats you stopped the car! You can now exit the car!")
action = input("Either start the car again or exit the car: ")
elif action == "exit":
print("Congrats you exited the car!")
break
else:
if action:
print("You typed an invalid response.")
action = input("Type either start, stop, exit to work this car: ").lower()
print("The end")
Note this will work fine on the first pass, since action = "" will bring you straight down to the new else block.
Let me correct your code
action = ""
started = 0
while action != 'exit':
action = input("Type either start, stop, exit to work this car: ").lower()
if action == "start":
if started:
print("The car is already started")
else:
started = 2
print("Congrats you started the car! You can now either stop the car or exit the car!")
action = input("Type either stop or exit to work this car: ").lower()
elif action == "stop":
if started == 2:
started = 1
elif started == 0:
print("You already stopped the car")
else:
started = 0
print("Congrats you stopped the car! You can now exit the car!")
action = input("Either start the car again or exit the car: ").lower()
elif action == "exit":
print("Congrats you exited the car!")
break
else:
action = input("You typed an invalid response, type either start, stop or exit:").lower()
print("The end")
You need to change action == input(...) to action = input(...)
I am trying to create a simple while loop that will run the commands start, stop, quit, and help. Start, stop, and help will just display some printed text. After they are run, I want it to keep going on to another command. However, on quit I want the whole program to stop.
input_command = input("> ").lower()
while input_command != "quit":
print(input_command)
if input_command == "start":
print("The car is ready! VROOM VROOM!")
print(input_command)
elif input_command == "stop":
print("Car stopped.")
elif input_command == "help":
print("""
start - starts the car
stop - stops the car
quit - exits the program
""")
else:
print("Sorry, I don't understand that...")
You never reassign input command so it only ever takes input once,
input_command = ''
while input_command != "quit":
input_command = input("> ").lower()