Python - Looping an Input [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
python, basic question on loops
how to let a raw_input repeat until I wanna quit?
I would like some help with Python please.
I'm writing a program in Py2.7.2, but am having some issues.
What I have so far is something like this:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
But after the user chooses either 1, 2, 3 or 4, the program automatically exits. Is there a way that I can loop the program back up so that it asks them again "What would you like to do?"; and so that this continues to happen, until the user exits the program.

You can accomplish that with a while loop. More info here:
http://wiki.python.org/moin/WhileLoop
Example code:
choice = ""
while choice != "exit":
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")

Use a While Loop -
choice = raw_input("What would you like to do (press q to quit)")
while choice != 'q':
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
choice = raw_input("What would you like to do (press q to quit)")

You need a loop:
while True:
choice = raw_input("What would you like to do")
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")

Personally this is how i would suggest you do it. I would put it into a while loop with the main being your program then it runs the exit statement after the first loop is done. This is a much cleaner way to do things as you can edit the choices without having to worry about the exit code having to be edited. :)
def main():
choice=str(raw_input('What would you like to do?'))
if choice == '1':
print("You chose 1")
elif choice == '2':
print("You chose 2")
elif choice == '3':
print("You chose 3")
else:
print("That is not a valid input.")
if __name__=='__main__':
choice2=""
while choice2 != 'quit':
main()
choice2=str(raw_input('Would you like to exit?: '))
if choice2=='y' or choice2=='ye' or choice2=='yes':
choice2='quit'
elif choice2== 'n' or choice2=='no':
pass

Related

I don't understand why I need to input "q" for n times of question generate, to quit program

I dont know why I have to input q n times of question generated to quit the program, what should I do so that the program closes instantly when I input q only once?
greetings = input("Hello, what should i call you? ")
def generate_again_or_quit():
while True:
option = input("Press any key to generate another question or Q to exit" ).lower()
if option == "q":
break
generate_questions()
def generate_questions():
print(random_questions_dict.get((random.randint(1, 30))))
generate_again_or_quit()
while True:
greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
if greetings2 == "yes":
generate_questions()
break
elif greetings2 == "no":
print("See you later...")
break
else:
print("Please answer with yes or no")
continue
As the comments suggest, pick iteration or recursion. Here's a recursion example for your case
import random
random_questions_dict = {1: "why", 2: "what", 3: "when", 4: "which", 5: "how"}
def generate_questions():
print(random_questions_dict.get((random.randint(1, 5))))
option = input("Press any key to generate another question or Q to exit" ).lower()
if option == "q":
return
generate_questions()
greetings = input("Hello, what should i call you? ")
while True:
greetings2 = input("Do you want me to generate some questions "+greetings+"?").lower()
if greetings2 == "yes":
generate_questions()
break
elif greetings2 == "no":
print("See you later...")
break
else:
print("Please answer with yes or no")
continue

Using a while loop with try catch python

I'm trying to catch an invalid input by the user in this function when the user runs the program. The idea is to use a try,exception block with a while loop to ensure that the code is continuously run until a valid input is made by the user, which is 1-5.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
raise Exception ("Invalid input")
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
I would advise against using exceptions for controlling flows.
Instead, I would keep iterating until the value is correct and use a return statement to indicate I'm done.
def door_one():
print("This door has many secrets let's explore it")
print("\nMake a choice to discover something")
print("1 2 3 4 5")
while True:
explore = input(" > ")
if explore not in ("1","2","3","4","5"):
continue
if explore == "1":
print("You fought a bear and died")
elif explore == "2" or explore == "3":
print("You become superman")
elif explore == "4":
print(f"Dance to save your life or a bear eats you")
suffer("HAHAHAHAHAHAHAHA!!!!!!")
elif explore == "5":
a_file = input("Please input a file name > ")
we_file(a_file)
suffer("HAHAHAHAHAHAHAHA!!!!!!")
return

Create Loop in if / else statement

I am trying to loop this function in the case the 'else' is reached but I'm having difficulties.
I tried while False and it doesn't do the print statements, I guess it kicks out of the function as soon as it ends up being false. I tried the True and I think that's the way to go but when it hits Else it just repeats. I'm thinking... maybe I need to do another Elif for the repeat of the whole function and the else as just an escape if needed.
def login(answer):
while False:
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")
while False:
should be
while True:
otherwise you never enter the loop
Further:
else:
print("I don't understand your selection")
should be:
else:
print("I don't understand your selection")
answer = input("enter a new choice")
You might even refactor your code to call the function without parameter:
def login():
while True:
answer = input("enter a choice (a for login or b for account creation")
if answer.lower() == "a":
print("You selected to Login")
print("What is your username? ")
break
elif answer.lower() == "b":
print("You selected to create an account")
print("Let's create an account.")
break
else:
print("I don't understand your selection")

Code printing stuff in the completely wrong order

```import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()```
It prints the rock paper or scissors, then it just goes would you like to play again. if you say yes, it then prints whether you won, lost or tied. what's wrong?
You call the Player-input only once, so once the Player made on decision calling start() will only generate a new random int. From what I understand you want to change the code into something like this, asking the player for input each time start() is called:
(Note that the pc before the definition is not needed aswell, since you reset it in start())
import random
from random import randint
def start():
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break
EDIT: As stated in the comment to your question by a different user, you shuold change the if to just if again.lower() = "yes" to be more clean. Alsoimport randomis not necessary if you callfrom random import randint` afterwards.
That's because 'randint' randomly initialize a number from 1-3 whenever invoked.
randint(1, 3)
So, whichever number the user enters, the function reinitialize the number and prints:
either "You win!", "You lose!", or "You draw!".
You probably want to read input inside start.
Also, your if statement will always be True because
if "yes":
will pass.
In any case you want to do something like again.lower() == 'yes'
You forgot to call your function after defined it.
You need to add start() before again.
Also if you want to play everytime the user said yes you need to had a loop
import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break;
Consider adding the first input to the function start, remove the first pc = randint and then call the function below its definition.

Using return in a function to assign a choice value in a menu

How can I use the choice variable in my menu() function to return the choice to my while loop?
def menu():
print("MENU")
print("1) Test")
print("2) Quit")
choice = int(input("\nChoose an option : "))
return choice
while choice != 2 :
menu()
if choice == 1 :
do_this
elif choice == 2 :
print("This program will terminate.")
break
else :
print("Invalid option... ")
you can simply do it like this
def menu():
print("MENU")
print("1) Test")
print("2) Quit")
choice = int(input("\nChoose an option : "))
return choice
while choice != 2 :
choice = menu()
if choice == 1 :
do_this
elif choice == 2 :
print("This program will terminate.")
break
else :
print("Invalid option... ")
You are getting the return value in your while loop with the variable choice in the line choice = menu() Then you can use that value in your while loop.

Categories

Resources