Exiting Program properly using two while loops? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to programming and I'm trying to make an option for the user to exit upon "yes" or y ,or "no" or "n", but I am having the worst luck in trying to do this. Could someone help me point out my error and hint at a better way to do this? I would really appreciate the assistance. Thank you.
Edit
I apologize about my vague posting. Let me be a little more clear in my question. Using two while loops to execute my program in a loop, I want to give the user a choice to whether they want to leave or redo the program. The program, however, doesn't exit properly, even though I've stated that "n" specifically is set to terminate the program. The code will, however, will loop back when I request or don't request to redo the main program, whether I enter "y" or "n".
I am confused as to what exactly is wrong with my loop, as it should close when I enter "n". What exactly is the problem with my loop's exit?
My coding
while True:
# Blah Blah Blah. Main program inserted here.
while True:
replay = input("Do another Calculation? (y/n)").lower()
if replay in ('y','n'):
break
print("Invalid input.")
if replay == 'y':
continue
else:
print("Good bye")
exit()

Your .lower should be .lower(). .lower() is a function, and calling it without parentheses doesn't do anything:
>>> string = 'No'
>>> string.lower
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower
>>> x
<built-in method lower of str object at 0x1005b2c60>
>>> x = string.lower()
>>> x
'no'
>>>
Also, you are checking for equality in replay == input(...). You just want a single = to assign:
>>> result = 0
>>> result == 4
False
>>> result = 4
>>> result == 4
True
>>>
You also have an unwanted : after print replay in your second while True loop.
This is a suggestion: instead of using replay in ("no, "n"), which is very unpythonic, use the built-in method startswith(char) to see if it starts with that character:
>>> string = "NO"
>>> string.lower().startswith("n")
True
>>> string = "yeS"
>>> string.lower().startswith("y")
True
>>>
This also works for input like naw, or yeah, etc.
Here is your edited code:
a = int(input("Enter the first number :"))
b = int(input("Enter the second number :"))
print("sum ---" + str(a+b))
print("difference ---" + str(a-b))
print("product ---" + str(a*b))
print("division ---" + str(a/b))
input()
while True:
print("Do you want to try again?")
while True:
replay = input("Do another Calculation? 'y' for yes. 'n' for no.").lower()
print(replay)
if replay.startswith('y') == True:
break
if replay.startswith('n') == True:
exit()
else:
print("I don't understand what you wrote. Please put in a better answer, such as 'Yes' or 'No'")

I see some syntax errors:
1) print replay should be print(replay)
2)if replay in ("yes","y") should be if replay in ("yes","y"):
3)if replay in ("no","n") should be if replay in ("no","n"):

Related

My loop continuously outputs without stopping [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I am trying to make this code break when the user enters "X" and allow it to continue when the user presses enter.
With what I have here, it stop and waits for enter input to output the next name I want it to output but doesn't break when I input X.
def Main():
userSent = input("Enter X to quit ").upper()`
while True:
if userSent == "X":`
break
else:
print(GenName())
input()
I tried getting rid of the input to fix the problem but then it just continuously went on nonstop. I expected it to break on X or else print GenName() and stop to wait for input.
The problem is that you only define userSent once, right before the loop starts. That means that if the first thing you enter isnt a capital X, then the program will never end. Try doing this:
def Main():
while True:
userSent = input("Enter X to quit ").upper()
if userSent == "X":
break
else:
print(GenName())
Within your loop, userSent is never updated. If the loop enters, it will never exit.
I suspect your last line is meant to be something like userSent = input().
You assign userSent value but you never updated it inside the while loop. You can use either of these versions:
def Main():
userSent = input("Enter X to quit ").upper()
while userSent != "X":
print(GenName())
userSent = input().upper()
def Main():
userSent = input("Enter X to quit ")
while userSent != "X" and userSent != "x":
print(GenName())
userSent = input()

Python variable not registering with if statement [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
When I ask the user if they would like to mega size their order, python says that it is a invalid entry. Dont mind the choice[] list, it is used elsewhere.
print("What size would you like?\nSmall ($1.50)\nMedium ($2.50)\nLarge ($3.50)\n")
main_choice=input("-").lower()
if main_choice=="small":
choice.append("small")
money+=1.50
pass
elif main_choice=="medium":
choice.append("medium")
money+=2.50
pass
elif main_choice=="large":
choice.append("large")
money+=3.50
os.system('clear')
t.sleep(1)
print("Would you like to Mega-Size your order for an extra $0.50? (yes/no)")
main_choice=input("-").lower
os.system('clear')
if main_choice=="yes":
money+=0.50
choice[2]="Mega-Size"
pass
elif main_choice=="no":
pass
else:
os.system('clear')
print(Fore.RED+"That is a invalid entry please try again.")
print(Style.RESET_ALL)
t.sleep(2)
os.system('clear')
fries_order()
else:
os.system('clear')
print(Fore.RED+"That is a invalid entry please try again.")
print(Style.RESET_ALL)
t.sleep(2)
os.system('clear')
fries_order()
os.system('clear')
str_money=str(money)
print("You ordered a",choice[0],"sandwich.")
print("You ordered a",choice[1],"drink.")
print("You ordered a",choice[2],"fry.")
print("Your cost so far is: $"+str_money)
I have tried to make the main_choice varible global, but to no avail.
You aren't calling lower() in
main_choice=input("-").lower
so main_choice is not a string but the bound function lower:
>>> main_choice=input("-").lower
-foo
>>> main_choice
<built-in method lower of str object at 0x106bebeb0>
>>> main_choice == "foo"
False
>>>
– you'll need
main_choice = input("-").lower()
to call lower() and have it return the lower-cased string for you to assign.
>>> main_choice=input("-").lower()
-foo
>>> main_choice
'foo'
>>> main_choice == "foo"
True
>>>

Python dice rolling game stuck on code, want to loop to restart if certain user input is met [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 2 years ago.
Improve this question
So I'm fairly new to this whole coding scene and I'm doing some beginner projects to build upon what I've learned.
Essentially what I'm trying to do is get the program to restart back at the top of the loop if the user wants to roll again, or accidently types something else that is not "yes" or "no".
In addition, is there a way to skip a certain line of code, so that way the user isn't asked if they want to roll twice?
Should I be using functions instead?
Couldn't find any info that helped me directly so thought I would ask, any info at all would be helpful, thanks!
import random
useless_varaible1 = 1
useless_varaible2 = 1
# this is the only way I know to set a while loop, I know yikes.
while useless_varaible1 == useless_varaible2:
lets_play = input('Do you wish to roll? Yes or no: ')
if lets_play.lower() == 'yes':
d1 = random.randint(1, 6)
d2 = random.randint(1, 6)
ask = input('Do you wish to roll again? ')
if ask.lower() == 'yes':
# How do I return to give the user another chance?
elif ask.lower() == 'no':
print('Alright, later!')
break
elif lets_play.lower() == 'no':
print('Alright, later!')
break
else:
print('Not any of the options, try again...')
# how do I return to the top to give the user another chance?
(Original code as image)
You've asked a couple of questions in one, but I'll try and answer them with an example. First off, to have an infinite running while loop, you can just set it to True (basically the same as your 1=1 statement, just easier).
Your second question regarding functions is typically yes - if some code needs to be repeated multiple times, it's usually good to extract it to a function.
Your third question regarding skipping a line of code - easiest way to do this is if/else statements, like you've already done. One thing that can be improved, is by using continue; it restarts the loop from the beginning, whereas break breaks out of the loop.
Here's a simple code example for your scenario:
import random
def roll():
print('First roll:', random.randint(1, 6))
print('Second roll:', random.randint(1, 6))
play = input('Do you wish to roll? Yes or no: \n')
while True:
if play.lower() == 'yes':
roll()
play = input('Do you wish to roll again? \n')
elif play.lower() == 'no':
print('Alright, later!')
break
else:
play = input('Not any of the options, try again... Yes or no: \n')
Hey I would do it like this
import random
useless_variable = 1
lets_play = input("Do you want to roll. yes or no: ")
if lets_play.lower() == "yes":
while useless_variable == 1:
useless_variable == 0
d1 = random.randint(1,6)
d2 = random.randint(1,6)
print("You got a: ", d1, "from the first dice")
print("You got a: ", d2, "from the seond dice")
ask = input("Wanna roll again(yes or no):")
if ask.lower() == "yes":
useless_variable = 1
else:
break
If you want to do an infinite loop then while True: Otherwise you can put in your while something like while condition == true and in your answer when is "no" change the condition to false.
I would do it like this
def roll():
if(lets_play.lower() == "yes"):
//Code here
elif lets_play.lower() == "no":
//Code here
else:
print("invalid")
while True:
lets_play = input("Roll?")
if lets_play.lower() == "exit":
break
else:
roll()

Yes or No answer from user with Validation and restart option?

(py) At the moment, the code below does not validate/output error messages when the user inputs something other than the two choices "y" and "n" because it's in a while loop.
again2=input("Would you like to calculate another GTIN-8 code? Type 'y' for Yes and 'n' for No. ").lower() #**
while again2 == "y":
print("\nOK! Thanks for using this GTIN-8 calculator!\n\n")
restart2()
break #Break ends the while loop
restart2()
I'm struggling to think of ways that will allow me to respond with an output when they input neither of the choices given. For example:
if again2 != "y" or "n"
print("Not a valid choice, try again")
#Here would be a statement that sends the program back to the line labelled with a **
So, when the user's input is not equal to "y" or "n" the program would return to the initial statement and ask the user to input again. Any ideas that still supports an efficient code with as little lines as possible? Thanks!
def get_choice(prompt="Enter y/n?",choices=["Y","y","n","N"],error="Invalid choice"):
while True:
result = input(prompt)
if result in choices: return result
print(error)
is probably a nice generic way to approach this problem
result = get_choice("Enter A,B, or C:",choices=list("ABCabc"),error="Thats not A or B or C")
you could of coarse make it not case sensitive... or add other types of criteria (e.g. must be an integer between 26 and 88)
A recursive solution:
def get_input():
ans = input('Y/N? ') #Use raw_input in python2
if ans.lower() in ('y', 'n'):
return ans
else:
print('Please try again.')
return get_input()
If they're really stubborn this will fail when it reaches maximum recursion depth (~900 wrong answers)

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Categories