Struggle to understand the logic behind the booleans inside the while loop - python

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.

Related

Why doesn't the while loop stop when the condition becomes False?

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.

how is True and False are working on this code

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.

When asking for an input, my boolean requires the input to be repeated before changing the value

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(...)

How to fix a while loop that goes on forever in Python?

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()

Ending an infinite loop issue (Python)

I am attempting to create a loop which a user can stop at the end of the program. I've tried various solutions, none of which have worked, all I have managed to do is create the loop but I can't seem to end it. I only recently started learning Python and I would be grateful if someone could enlighten me on this issue.
def main():
while True:
NoChild = int(0)
NoAdult = int(0)
NoDays = int(0)
AdultCost = int(0)
ChildCost = int(0)
FinalCost = int(0)
print ("Welcome to Superslides!")
print ("The theme park with the biggest water slide in Europe.")
NoAdult = int(raw_input("How many adults are there?"))
NoChild = int(raw_input("How many children are there?"))
NoDays = int(raw_input("How many days will you be at the theme park?"))
WeekDay = (raw_input("Will you be attending the park on a weekday? (Yes/No)"))
if WeekDay == "Yes":
AdultCost = NoAdult * 5
elif WeekDay == "No":
AdultCost = NoAdult * 10
ChildCost = NoChild * 5
FinalCost = (AdultCost + ChildCost)*NoDays
print ("Order Summary")
print("Number of Adults: ",NoAdult,"Cost: ",AdultCost)
print("Number of Children: ",NoChild,"Cost: ",ChildCost)
print("Your final total is:",FinalCost)
print("Have a nice day at SuperSlides!")
again = raw_input("Would you like to process another customer? (Yes/No)")
if again =="No":
print("Goodbye!")
return
elif again =="Yes":
print("Next Customer.")
else:
print("You should enter either Yes or No.")
if __name__=="__main__":
main()
You can change the return to break and it will exit the while loop
if again =="No":
print("Goodbye!")
break
Instead of this:
while True:
You should use this:
again = True
while again:
...
usrIn = raw_input("Would you like to process another customer? y/n")
if usrIn == 'y':
again = True
else
again = False
I just made it default to False, but you can always just make it ask the user for a new input if they don't enter y or n.
I checked your code with python 3.5 and it worked after I changed the raw_input to input, since input in 3.5 is the raw_input of 2.7. Since you're using print() as a function, you should have an import of the print function from future package in your import section. I can't see no import section in your script.
What exactly doesn't work?
Additionally: It's a good habit to end a command line application by exiting with an exit code instead of breaking and ending. So you would have to
import sys
in the import section of your python script and when checking for ending the program by the user, do a
if again == "No":
print("Good Bye")
sys.exit(0)
This gives you the opportunity in case of an error to exit with a different exit code.
Change this code snippet
if again =="No":
print("Goodbye!")
exit() #this will close the program
elif again =="Yes":
print("Next Customer.")
exit()#this will close the program
else:
print("You should enter either Yes or No.")

Categories