How to stop an endless loop? [duplicate] - python

This question already has answers here:
how to stop a for loop
(9 answers)
Closed 6 years ago.
I am making a script game and use this code for multiple choice.
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
elif d1a == "Q" :
break
After this happens,If you type A or B it will print the desired text and then ask you again "Do you want to befriend fred?" etc.

You can simply add break statements to each conditional:
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
break
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
break
elif d1a == "Q" :
break
Also if you want to leave the loop after one iteration the loop isn't necessary. However, I assume you're looping until you get the correct input, in which case it might be nice to tell your player that the input was incorrect:
while True:
d1a = input ("Do you want to: A) Befriend Fred. B) Be mean to Fred. [A/B]? : ")
if d1a == "A":
print ("You befriend fred. You now have a friend..")
break
elif d1a == "B":
print ("You angered Fred. He kills you. RIP.")
break
else:
print("Incorrect input")

Related

If I add OR options to IF, the code doesn't run properly [duplicate]

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 last month.
When I put in line 7 or the code doesn't work as intended.
Can someone please tell me the reason for that?
# x = int(input("Insert price for your product :"))
x=100
print ("Does your product include taxes?")
# answer = input(" yes or no ")
answer = "no"
if answer == "yes" or "Yes" or "YES":
print ("final price is : ", x, "\n the tax is :" ,x*0.17)
elif answer == "no":
print ("final price is : ", x*1.17, "\n the taxes is ", x*0.17)
else:
print ("Your answer is not according to the dictionnary - try again")
I expect that any input for the word YES will work for the if in the code.
Try:
if answer in ["yes","Yes","YES"]:
OR
if answer == "yes" or answer=="Yes" or answer=="YES":
Instead of.
if answer == "yes" or "Yes" or "YES":
instead of using if answer == "yes" or "Yes" or "YES":. you should try
if answer == "yes" or answer == "Yes" or answer == "YES":.
OR use python built-in method called lower(), so that you can lowercase your input
x = int(input("Insert price for your product :"))
print ("Does your product include taxes?")
answer = input(" yes or no ").lower()
if answer == "yes":
print ("finel price is : ", x, "\nthe tax is :" ,x*0.17)
elif answer == "no":
print ("finel price is : ", x*1.17, "\nthe taxes is ", x*0.17)
else:
print ("Your answer is not according to the dictionary - try agin")
It's an issue with syntax.
if answer == "yes" or "Yes" or "YES":
In this context in Python you need to spell out each time what variable you are using, for example:
if answer == "yes" or answer== "Yes" or answer== "YES":
or you can format it a different way such as:
answer = answer.lower()
if answer == "yes":
print ("final price is : ", x, "\nthe tax is : " , x*0.17)
elif answer == "no":
print ("final price is : ", x*1.17, "\nthe tax is : ", x*0.17)
else:
print ("Your answer is not according to the dictionary - try again")
this solution will change answer to be all lowercase which allows people to also write things such as YeS or yeS. This also keeps the code from looking cluttered.

looping the program when a condition is not met [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
print_list=input("Do you wish to print list \n:")
if print_list == "yes":
for item in List:
print (item , "%2.f" %(Speed),"m/s")
elif print_list == "no":
print ("Thank you")
if print_list != "yes" or "no":
while True:
print ("Invalid Input")
break
this is what happened:
Do you wish to print list
:hhh
Invalid Input
Press "Enter Key" when the vehicle passes Sensor 1
:
What I was hoping was for the program to ask the question "Do you wish to print list", when the user input is invalid.
If you want the first statement to happen again then it has to be inside the loop. Basically all of this needs to be inside the while loop. And the break will cause the loop to end, so definitely don't put it after invalid input since you want the user to be asked again.
while True:
print_list=input("Do you wish to print list \n:")
if print_list == "yes":
for item in List:
print (item , "%2.f" %(Speed),"m/s")
break
elif print_list == "no":
print ("Thank you")
break
else:
print ("Invalid Input\n")

How to flatten nested IF statements which all contain strings?

I'm making a Choose Your Own Text Adventure game which, so far, contains far too much nesting. Example code is below = mine's in the same format, just with far more nesting - sometimes approaching 10 layers deep.
My question is: Any way to flatten it? The strings mean I need every IF statement to print something every time it's valid, so I can't just use 'AND' like this:
if A and B:
do something
elif C and D:
do something else
I've thought of putting the parts that repeat in their own functions, but then that won't improve readability in this case - at least, not that I can figure out.
Help?
print "First String"
choice = raw_input("Choose A or B")
if choice == "A":
print "You Chose A"
choice = raw_input("Choose C or D")
if choice == "C":
print "You Chose C"
choice = raw_input("Choose E or F")
if choice == "E" or choice == "F":
print "END"
elif choice == "D":
print "You Chose D"
choice = raw_input("Choose G or H")
if choice == "G" or choice == "H":
print "END"
elif choice == "B":
print "You Chose B"
choice = raw_input("Choose I or J")
if choice == "I":
print "You Chose I"
choice = raw_input("Choose C or D")
if choice == "C":
print "You Chose C"
choice = raw_input("Choose E or F")
if choice == "E" or choice == "F":
print "END"
elif choice == "D":
print "You Chose D"
choice = raw_input("Choose G or H")
if choice == "G":
print "END"
elif choice == "H":
print "You Chose H"
choice = raw_input("Choose K or L")
if choice == "K" or choice == "L":
print "END"
If the mappings are straightforward, like , lets say , if I chose A first, i can chose C or D , also if I chose B first I can chose C or E. Now when in C , irrespective of whether the first choice was A or B, the choices you get are same. Then you can use recursion along with a dictionary like -
dict = {'-1':['A','B'], 'A' : ['C','D'] , 'B':['I','J'], 'C':['E','F'] ..}
Then a recursive function like -
def choose(previousChoice, num):
print str(num) + " String"
choice = raw_input("Choose " + ' or '.join(dict[previousChoice]) + " :")
if dict.get(choice) != None and len(dict.get(choice)) > 0:
choose(choice, num + 1)
In the above example you start with -
choose('-1',1)

Basic Calculator program not working in Python idle [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
loop = 1
choice = 0 #holds the user choice for menu
while (loop == 1):
print ("Welcome to calci.py")
print ("your options are:")
print (" ")
print ("1. Addition")
print ("2. Subtraction")
print ("3. Multiplication")
print ("4. Division")
print ("5. Quit calculator.py")
print (" ")
choice = input("Choose your option: ")
if (choice == 1):
add1 = input("Add this: ")
add2 = input("to this: ")
print (add1, "+", add2, "=", add1 + add2)
elif (choice == 2):
sub2 = input("Subtract this: ")
sub1 = input("from this: ")
print (sub1, "-", sub2, "=", sub1 - sub2)
elif (choice == 3):
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print (mul1, "*", mul2, "=", mul1 * mul2)
elif (choice == 4):
div1 = input("Divide this: ")
div2 = input("by this: ")
print (div1, "/", div2, "=", div1 / div2)
elif (choice == 5):
loop = 0
print ("Thankyou for using calci.py!")
I am new to the python world, I have written and compiled the calculator code, but its not working,Need help!!
Your code:
choice = input("Choose your option: ")
if (choice == 1):
here input will return string output. So in your if condition you will need to do like:
choice = input("Choose your option: ")
if (choice == '1'):
Then it will work. But remember it's will concat two string in above example. So may be you will need to convert that string to integer and then perform your arithmetic.
So you could use like
intchoice = int(choice)
if (intchoice == 1):
similarly you need to follow for your add1/add2 and other input parameters.
I attempted to run your code in Terminal, and it infinitely loops as given.
You initially set choice to zero, but your code does not handle zero, so it doesn't know what to do so it just loops.
Try adding an else block and the end of your elif statements to catch anything that elif doesn't account for.
EX:
else:
print("Error")
loop=0
I see your using a while loop to try and make the program run continually until the user quits.
try using input() or raw_input() to get user choices for the operation. Other then that great job!

Repeat a function

from sys import exit
def answer():
answer = raw_input("> ")
if answer == "Yes" or answer == "yes":
#going to next
joint()
elif answer == "No" or answer == "no":
print "You still have something, I know..."
again()
else:
fubar()
def again():
again = raw_input("> ")
if again == "Yes" or again == "yes":
#going to next
joint()
elif again == "No" or again == "no":
print "You still have something, I know..."
else:
fubar()
def fuck():
print "Fubar'd!"
def joint():
print "To be continue..."
def question():
print "Hi duuuude..."
raw_input("To say 'Hi' press Enter")
print "Can you help me?"
answer()
question()
Hi, can you help me with this? I`m trying to repeat the function "answer", when I get answer "NO". Im want to escape function "again"... And also is there a way to escape "answer == "Yes" or answer == "yes": " so no matter I write capital or small letter to accept the answer and not to write like a noob "Yes" or "yes"?
This is usually achieved with a while loop.
Edit: As pointed out, while loops are nice and clear, and avoid recursion limits.
Never thought a simple answer would generate so many votes....
Lets give you an example
while True:
ans = raw_input("Enter only y or n to continue").strip().lower()
if ans == "y":
print "Done!"
break
elif ans == "n":
print "No?"
else:
print "Not valid input."
The simplest solution to your problem is remove your again function, and recurse:
def answer():
ans = raw_input("> ")
if ans == "Yes" or ans == "yes":
#going to next
joint()
elif ans == "No" or ans == "no":
print "You still have something, I know..."
answer() # again()
else:
fubar()
I had to rename your answer variable to ans so that it didn't clash with the function name.
For the second question, you want either:
if answer.lower() == "yes":
or
if answer in ("Yes", "yes"):

Categories

Resources