My python program doesn't quit, keeps running loop - python

I'm writing a short program where users pick otions, I wrote a function (Yes/No) for the user to pick wether to return to home or quit program, when the user picks "No", the program is supposed to display a goodbye! message and quit but the loop seems to display the goodbye message but still prompting the user if they want to quit or not.
This is my function
def exit_home():
while True:
user = input("home or exit? (Yes/No)").lower()
if user == "yes":
main()
elif choice == "no":
print(quit)
quit()
print("Bye! ")
continue
else:
break
print("enter a valid input (Yes or No)")
And I get the result below
home or exit? (Yes/No)no
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Bye!
home or exit? (Yes/No)
Also if there's a neater way of let user exit the program without printing the <IPython.core blah blah blah> I would appreciate the sugesstion.
Thanks

There are several issues in your code:
Remove print(quit) to get rid of
<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10>
Use return to break the loop instead of continue
print after break doesn't make sense because print will never be executed
break doesn't make sense because it breaks the loop, but you want to get into another interation
Corrected code:
while True:
action = input("home or exit? (Yes/No) ").lower()
if action == "yes":
print("call main function...")
elif action == "no":
print("Bye! ")
break
else:
print("enter a valid input (Yes or No)")
Sample output:
home or exit? (Yes/No) yes
call main function...
home or exit? (Yes/No) maybe
enter a valid input (Yes or No)
home or exit? (Yes/No) no
Bye!

<IPython.core.autocall.ZMQExitAutocall object at 0x7fa9c096df10> was shown because you printed out the function.
Just this should work.
import sys
elif choice == "no":
print("Bye! ")
sys.exit()

Related

I'm trying to write a simple whatsapp bot with selenium but the messaging loop won't work properly. What is the problem?

textbar = driver.find_element("xpath",'//*[#id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p')
while(True):
message = input("Please enter the text you want to send to the selected person to stop the program type -exit- : ")
textbar.send_keys(message)
if(message == "exit"):
break
textbar.send_keys(Keys.RETURN)
In your code, you're calling textbar.send_keys(message) before checking if the message is exit. You should move up your if statement so that you exit the program sooner. And put the find_element inside the loop to avoid StaleElementReferenceException. Eg:
while(True):
message = input("Please enter the text you want to send to the selected person. To stop the program, type -exit- : ")
if(message == "exit"):
break
textbar = driver.find_element("xpath",'//*[#id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]/p')
textbar.send_keys(message)
textbar.send_keys(Keys.RETURN)

How do I make a function that googles the input from the user, with while loop unless I type 'exit' which breaks it?Do I need to define the variable?

I tried making a while loop, however, I can't break it. I am new to programming and maybe I am bitting more than I can chew, but I would be grateful if someone could help me. I am using pywhatkit and I have a problem defining the searching variable.
import pywhatkit as pwt
def searching_mode():
searching = (input(''))
while True:
print(f"Searching ...")
if searching == pwt.search(input('')):
continue
else:
searching == (input('exit'))
break
searching_mode()
Your input should be in while loop so it can continue execute the input when there's no input or break when the input is 'exit'. Try this:
import pywhatkit as pwt
def searching_mode():
while True:
searching = input('Search for? (type "exit" to exit) : ')
if 'exit' in searching:
break
elif not searching:
continue
else:
print(f'Searching for "{searching}"...')
pwt.search(searching)
searching_mode()
Output:
Search for? (type "exit" to exit) : python course
Searching for "python course"...
Search for? (type "exit" to exit) :
Search for? (type "exit" to exit) : stackoverflow python while loop
Searching for "stackoverflow python while loop"...
Search for? (type "exit" to exit) : exit
Process finished with exit code 0
Hi if you can give more information about what you want to achiev and give full script can help better. But you can try setting up a switch to break a loop for example;
def searching_mode():
switch = True:
searching = (input(''))
while switch:
print(f"Searching ...")
if searching == pwt.search(input('')):
continue
else:
searching == (input('exit'))
switch = False
searching_mode()
While loop will continue to run if you construct like "while True", so you can setup a condition to break from it. by using
while switch:
if condition1:
#do something:
else:
#do this
switch = False
# so next time it

How to continue after achieving if statement in python

When the program achieve any of the if statements the program stops. How to keep it running after achieving an if statement?
def main():
print("Hello i'm your new virtual messenger:")
inside = input();
if inside == "Hello" or "Hi" or "Hey" or "Yo":
print("hello !")
if inside == "Whats's your name":
print("My name is Raito")
if inside == "Who programmed you" or "Who made you" or "Who've made you":
print("it's you LOL, because i think no one will use this")
if inside =="What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, i told you, im waiting to be updated")
if __name__=='__main__':
main()
Probably you are looking for the while loop, so you want something like this:
def main():
print("Hello I'm your new virtual messenger:")
while True:
inside = input();
if inside in ["Hello","Hi","Hey","Yo"]:
print("hello !")
elif inside == "Whats's your name":
print("My name is Raito")
elif inside in ["Who programmed you","Who made you","Who've made you"]:
print("it's you LOL, because I think no one will use this")
elif inside == "What can you do":
print("Right now nothing special, died waiting to be updated")
else:
print("I Don't know how to answer your question, I told you, I'm waiting to be updated")
if __name__ == '__main__':
main()
With this code you loop forever.
If you want to exit the loop at some point, for example if you read "Exit" from the input, you can use the keyword break (which let you continue with the code after the while loop) like this:
elif inside == "Exit":
break
This lines of code should be as the others "elif" between the "if" and the "else".

run the code multiple times in python 3.6

I tried to make it only ask "do you want to continue" 3 times but it doesn't seem to work, it just kept on running. How do I fix this? It is a chat-response program which the computer askes one question and the user response.
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
This is the code I have written for it. but it does not work.
import random
name = input("What is your name? ")
def restart():
restart=input('do you want to continue? ')
if restart=='yes':
choice()
else:
print("ok, see you later!")
exit()
def feeling():
response = input("How are you feeling right now {name}?".format(name=name))
if response == "tired":
tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
print(random.choice(tired))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def homesick():
response = input("Do you miss your home? ")
if response == "yes":
yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
print(random.choice(yes))
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def miss():
response = input("Who do you miss?")
if response == "my mom":
print("Mom will be in town soon")
restart()
else:
print("Sorry, I don't understand what you mean by "+response+".")
exit()
def choice():
prompts = [feeling, homesick, miss]
random.choice(prompts)()
for item in range(3):
choice()
The comment from darvark is correct. If you want to keep the rest of your code the same, then I would just modify the restart function to look something like this:
import sys
def restart():
if input('do you want to continue? ') != 'yes':
sys.exit()
This way, if the user responds with anything other than 'yes', the program will quit; however, if they respond with 'yes', then the call to restart will simply do nothing, and your loop should advance to the next iteration.
One more note: It is not recommended to call the exit function within a program, since it is just a helper function to be used when you're running the Python interpreter. Within a program, you should import the sys module and call sys.exit. Source: Difference between exit() and sys.exit() in Python

My python play again feature does not work

def playAgain():
while True:
try:
replay = input("Do you want to play again? ").lower() #Asking user to play again
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
continue
if replay in ("yes","y","true","t"):
main()
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
def main():
print ("Hello")
playAgain()
main()
For my homework, I am required to make a quiz. I have got it all to work accept for the play again feature which you can see above. I am having trouble exiting the program. If I type in no the first time it asks me do you want to play again it will exit correctly. The problem I have is if I type in yes the first time and then no the second time, it will not exit. The program will ask me the question again a third time where if I press no it will exit correctly.
I know the solution is probably very obvious but I can't seem to fix it.
In your code, main calls playAgain. Then, if you select to play again, playAgain calls main recursively.
main -> playAgain -> main -> playAgain
^^^
If you return here, only the second playAgain exits, then the program goes back to the main loop in the first playAgain.
To fix it, add return to exit the main loop when the user selects to play again as well:
if replay in ("yes","y","true","t"):
main()
return # here
For Python 2.7:
def playAgain():
while True:
try:
replay = raw_input("Do you want to play again? ").lower() #Asking user to play again
if replay in ("yes","y","true","t"):
main()
return
elif replay in ("no","n","false","f"):
print ("Goodbye")
return
else: #If input is invalid will ask again
print("Invalid entry, Please enter yes or no")
except ValueError:
print("Sorry, Invalid Entry") #If response invalid, will ask again
def main():
print ("Hello")
playAgain()
main()

Categories