While true loop with only one prompt - python

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:
...

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.

Programming an atm machine

My assignment is to create an ATM-type program. Below is my main function (not including the deposit, withdraw, and check balance functions). When I go to run this code, the program loops the pin function repeatedly, even when I enter 0 or 1234. It repeatedly instructs the user to enter their pin. I think I have all of the indentation right, but I guess I'm messing up somewhere in the code.
def main():
pin_number = input("Please enter your pin number")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop == True
if pin_number == "1234":
stop == False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
In your if statements, you should be using = not ==. The first is used for assigning values to variables, like you are trying to do. The second is used to compare if two values are equal and returns a boolean (true/false).
Your code
if stop != True:
will run the code inside the loop if the variable stop is False (the user has entered the wrong code). However, you want to run the code if stop is True.
Therefore, use this code:
if stop == True:
this will run the encased code when stop is True (user has entered correct code)
EDIT:
My apologies. The above answer regards the code following this code:
if pin_number == "1234":
stop = False

I have written a code in Python where even if i am using a break statement and continue still its going into an infinite loop in Python:

The below code is running however when I am trying to exit out of the code it goes into an infinite loop where even if i type in 1 still it does not break out of the loop. I am a beginner in Python please can anyone help me??
Here is my code,
import urllib2
import sys
urlToRead = ('https://www.google.com')
crawledWebLinks = {}
while urlToRead !='':
try:
urlToRead = raw_input('Please enter the Next weblink to crawl')
if urlToRead == '':
print ('Ok Existing the Loop')
break
shortName = raw_input('Please enter a short Name for the Url to Read ' + urlToRead)
webfile = urllib2.urlopen(urlToRead).read()
crawledWebLinks[shortname] = webfile
except:
print (sys.exc_info()[0])
stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break
else:
print ('lets continue')
continue
print (crawledWebLinks.keys())
The following few lines are the ones causing problem,
stopOrproceed = raw_input('You want to Stop or Continue, Please type in 1 to stop or anything else to Continue')
if stopOrproceed == 1:
print ('Okies we are stopping')
break
You see raw_input gets input and stores it as a string. So after getting the value from user. your stopOrproceed variable would have "1"
And when you check for stopOrproceed==1 --> "1"==1. Which is definitely not equal in Python. So always false is evaluated And hence the control never goes inside the if and thus you never break.
Try changing that to this,
if stopOrproceed == "1":
print ('Okies we are stopping')
break

is a While True or If Statement best to execute one function before moving to the next

I am stuck on a simple issue. I am attempting to ask the user to choose a desired function from a list. This inputted user string will invoke the chosen function until it finishes running. (It is a lighting sequence). After this sequence ends, I would like to ask the user if he or she wishes to choose another function. If so, continue. If not, exit the code.
I cannot decide if a while true or if statement is the best to achieve this.
Here is my code:
# random functions
def rainbow():
print 'rainbow'
def clover():
print 'clover'
def foo():
print 'eggs'
if __name__ == '__main__':
# here are some random initializations
print 'ctr-c to quit'
user_input = input("choose from the following: ")
if user_input == 'rainbow':
print 'generating'
rainbow()
rainbow()
rainbow()
user_input = input('choose another')
if user_input == 'foo':
clover()
clover()
I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:
while True:
user_input = input('...')
if "good result"
break
else:
continue
while True:
user_input = input("choose from the following: ")
if user_input == "condition a":
do something
elif user_input == "condition b":
do something..
elif any(user_input == keyword for keyword in ["q", "quit"]):
# when meet any quit keyword, use break to terminate the loop
break
else:
# when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
continue
while True can meet your requirement. you can use if-elif-else clauses to do different works.

Categories