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".
Related
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()
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
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
I made a program that asks you at the end for a restart.
I import os and used os.execl(sys.executable, sys.executable, * sys.argv)
but nothing happened, why?
Here's the code:
restart = input("\nDo you want to restart the program? [y/n] > ")
if str(restart) == str("y"):
os.execl(sys.executable, sys.executable, * sys.argv) # Nothing hapens
else:
print("\nThe program will be closed...")
sys.exit(0)
import os
import sys
restart = input("\nDo you want to restart the program? [y/n] > ")
if restart == "y":
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
else:
print("\nThe program will be closed...")
sys.exit(0)
os.execl(path, arg0, arg1, ...)
sys.executable: python executeable
os.path.abspath(__file__): the python code file you are running.
*sys.argv: remaining argument
It will execute the program again like python XX.py arg1 arg2.
Maybe os.execv will work but why not use directly using os.system('python "filename.py"') if you have environment and path variable set something like :
import os
print("Hello World!")
result=input("\nDo you want to restart the program? [y/n] > ")
if result=='y':
os.system('python "C:/Users/Desktop/PYTHON BEST/Hackerrank.py"')
else:
print("\nThe program will be closed...")
try using;
while True:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
break
or
retry = True
while retry:
answer = input("\nDo you want to restart the program? [y/n] > ")
if answer == "n":
print("\nOk, Bye!")
retry = False
It is a way that you can easily modify to your liking, and it also means that you can load variables once instead of loading them every time you restart. This is just a way to do it without any libraries. You indent all your code and put it in a while loop, and that while loop determines whether your code restarts or not. To exit it, you put in a break or change a variable. It is easiest because you don't have to understand a new library.
Just import the program you want to restart and run it under the desired condition like this
Title: hello. py
import hello
if (enter generic condition here):
hello
os.execv(sys.executable, ['python'] + sys.argv)
solved the problem.
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()