This question already has answers here:
While loop won't stop in python
(3 answers)
Closed 3 years ago.
I am fairly new to coding.
So i am in the process of making a program and i have not quite finished it. But i have added an option where the program starts again if the user selects yes, if the user selects no the program should say good bye and stop. But when no is selected it says goodbye but starts the program again. Could someone tell me if im doing something wrong
When no is selected is starts the program again.
restart = True
while restart == True:
while True:
print(' Welcome to My Program')
print('Please Choose an Option')
print('Option 1: Enter RLE')
print('Option 2: Display ASCII Art')
print('Option 3: Convert to ASCII Art')
print('Option 4: Convert to RLE')
print('Option 5: Quit')
option = int(input('Choose an Option: '))
if option ==1:
Split=(list(input("Enter string: ")))
Split.append("")
a = 0
for i in range(len(Split)):
try:
if (Split[i] in Split) >0:
a = a + 1
if Split[i] != Split[i+1]:
print(Split[i],a)
a = 0
except IndexError:
print()
elif option == 2:
print("Hello")
elif option == 3:
print("Hello")
elif option == 4:
print("Hello")
elif option == 5:
print ('Ending Program')
exit()
else:
print('Invalid Input')
while True:
answer = str(input('Would You Like to Run The Program Again? (y/n): '))
if answer in ('y', 'n'):
break
print ("Invalid input.")
if answer == 'y':
restart == True
else:
print ('Goodbye')
restart == False
break
When no is selected is starts the program again.
The first while True: after while restart == True: has created an infinite loop. Try getting rid of that and just putting your program inside the first while loop.
Related
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 3 months ago.
I was using a yes/no loop to make an infinite loop which would end when user enters no or No but the program was not working properly. I know the what the error is but i don't know why is it occuring like this. Can anyone tell how to fix the error without changing my initial program
when i use this code it works but when i use if a=='yes' or 'Yes' and elif a=='no' or 'No' in the somehow the output shows the print statement of the if statement even when i enter no.
My program without the OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes':
print("enter the program")
elif a=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
My initial program with OR condition
while True:
a = input("Enter yes/no to continue")
if a=='yes' or 'Yes':
print("enter the program")
elif a=='no' or 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
In an or statement you have to compare a with the value in all expressions:
while True:
a = input("Enter yes/no to continue")
if a == 'yes' or a == 'Yes':
print("enter the program")
elif a == 'no' or a == 'No':
print("EXIT")
break
else:
print("Enter either yes/no")
A more pythonic way is to use .lower() in your case. For example:
a == 'yes' or a == 'Yes' # is equeal to:
a.lower() == 'yes'
You have a few options:
while True:
a = input("Enter yes/no to continue")
if a.lower()=='yes':
print("enter the program")
elif a.lower()=='no':
print("EXIT")
break
else:
print("Enter either yes/no")
or you can do this:
while True:
a = input("Enter yes/no to continue")
if a=='yes' or a=='Yes':
print("enter the program")
elif a=='no' or a=='No':
print("EXIT")
break
else:
print("Enter either yes/no")
When you use or, you should write complete condition again.
Here if you want to check a=="Yes" also, you should declare it completely.
if a == 'yes' or a == 'Yes':
...
You can also use this:
if a.lower() == 'yes'
...
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I'm coding a big project that has many functions. I want my code to restart functions where errors occur due to user input, to illustrate what I mean I have made this short code:
def myfunction():
UserInput = int(input("Enter 1 or 2"))
if UserInput == 1:
print("hello")
elif UserInput == 2:
print("Bye")
else:
print("Error!, Please choose 1 or 2")
#I want it to restart myfunction()
thanks.
As #ti7 commented you better use a while loop and not call your function again on error (recursion)
I don't know what you want to do with the input but as I see you do not need to convert it to an integer to check if it's 1 or 2. Because you can get a ValueError if the input is not convertible to integer.
What you'll do, get the input, use a while loop and check if the input is not "1" and "2"
def myfunction():
UserInput = input("Enter 1 or 2")
while UserInput != "1" and UserInput != "2":
UserInput = input("Enter 1 or 2")
if UserInput == "1":
print("hello")
elif UserInput == "2":
print("Bye")
else:
print("Can't be else")
Simple, just call the function. (You will want the extra UserInput so you can read the text)
def myfunction():
UserInput = int(input("Enter 1 or 2"))
if UserInput == 1:
print("hello")
elif UserInput == 2:
print("Bye")
else:
print("Error!, Please choose 1 or 2")
UserInput = input('Press anything to continue. ')
myfunction()
List item
i want to let the user type 1 , 2 or quit otherwise i want to put him to type again one of them. everything works with 1 and 2 but for quit doesn't work, and i also want if he types quit to use sys.exit('message') - this part is from a function where u can choose your difficulty level. also its a hangman game. tanks
Sloved!!
import sys
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").lower()
try:
if difficulty == '1':
print('Easy game mode is set!')
elif difficulty =='2':
print('Hard game mode is set!')
elif difficulty =='quit':
print('Sheeeeeeeeeeeeeeesh')
except:
continue
if difficulty == '1' or difficulty =='2':
break
elif difficulty == 'quit':
sys.exit('byeeeee')
break
#elif difficulty
else:
print('invalid ')
You are storing the user input in uppercase for difficulty variable.
And in if condition verifying in lowercase.
So remove the upper() from
input("Choose difficulty 1 for easy 2 for hard: ").upper()
try: and except: is probably not what you want to use here because you won't get a ValueError and thus the except does not execute. Maybe try something like:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
It breaks the loop when the correct input is given, and keeps looping otherwise.
If you would LIKE to have a ValueError when they enter a wrong input you can use raise like so:
while True:
difficulty = input("Choose difficulty 1 for easy 2 for hard: ").upper()
if difficulty == '1':
print('Easy game mode is set!')
break
elif difficulty =='2':
print('Hard game mode is set!')
break
elif difficulty =='QUIT':
print('bye')
break
else:
print("you can only choose 1, 2, or quit.")
raise ValueError #notice the additional line here
I am having trouble with the following code:
def main():
stringsList = [] # empty list to hold inputted strings
getInput(stringsList)
def getInput(stringsList):
minWords = 0
while minWords < 8:
stringInput = str(input('Enter a word, x to exit: '))
stringsList.append(stringInput)
minWords = minWords + 1
if stringInput == 'x':
break
print('Exiting application')
# ask user to select modified list
userChoice = input(
'''
Sort Ascending: 1
Sort Descending: 2
(Choose an option)
'''
)
if userChoice == '1':
SortByIncreasingLength(stringsList)
elif userChoice == '2':
My intent is that if the user enters "x", then the loop terminates and should print "Exiting application".
Instead, it continues on to the userChoice variable which will be a menu system. Here's a sample output:
Enter a word, x to exit: x
Exiting application
Sort Ascending: 1
Sort Descending: 2
(Choose an option)
What am I missing? I can't seem to put a finger on why this shouldn't work as I expect it to.
A break statement will exit the loop (and go to the next line in the function that is outside the loop), but it will not exit the program. If you want to exit the program when the user enters 'x', you want to call return (this will exit the function) or exit() (to exit python) instead
Here's the fixed code:
def getInput(stringsList):
minWords = 0
while minWords < 8:
stringInput = str(input('Enter a word, x to exit: '))
stringsList.append(stringInput)
minWords = minWords + 1
if stringInput == 'x':
print('Exiting application')
exit()
You must put all your code inside the while loop to exit when break is called.
def validate(choice):
try:
if choice == 1 or choice == 2 or choice == 3 or choice == 4 or choice == 5 or choice == 6 or choice == 7 or choice == 8:
if choice==1:
extrasquare()
elif choice==2:
drawastar()
elif choice==3:
drawit()
elif choice==4:
circle()
elif choice==5:
square()
elif choice==6:
turtle.clear()
elif choice==7:
turtle.bye()
elif choice==8:
import sys #exit from program
sys.exit() #might not work in some versions of idlex
loop = 700076
except:
loop=8
print("Error")
while loop == 1:
#print options for user
print("----------------------------")
print("Hello")
print("Here's you options")
print("1- to draw a set of squares(extra picture)")
print("2-to draw 10 stars")
print("3-to draw nine rectangles")
print("4-to draw a random number of random circles")
print("5-to draw a square motion")
print("6-to Erase everything")
print("7-to exit from turtle")
print("8-to exit from python")
print(" ")
choice = int(input("What would you like to do? Please enter a number:"))
validate(choice)
I need to use try-except to validate input data but obviously I do something wrong. I need to stop loop and print error if input was >=9. Could you help me guys? I really do not know what to write else
You will find this sort of problem a lot easier using a dictionary:
def validate(choice):
options = {
1: extrasquare,
2: drawastar,
3: drawit,
4: circle,
5: square,
6: turtle.clear,
7: turtle.bye,
8: exit # Move your exit action to a separate function for simplicity
}
if choice in options:
options[choice]()
else:
print "Error: %i is not a recognized choice" % i
Your existing code won't raise an exception since you only try a lot of ifs and dont hit an exception condition.
You could do the same with a try by changing the last lines two:
try:
options[choice]()
except KeyError:
print "Error : %i is not a recognized choice" % choice
However it doesn't really enhance the code .