This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 2 years ago.
I keep getting the error "break is outside of loop" I've read a lot and I'm clearly missing something.
again = input(" again? y/n")
if again == "y" or \
again == "Y":
main()
else:
print("Thanks for using my calculator!")
again = input("Would you like to calculate again? y/n")
if again == "y" or \
again == "Y":
main()
else:
print("Thanks!")
#BREAK !!!!????
main()
while(True):
again = input("Would you like to calculate again? y/n")
if again == "y" or again == "Y":
main()
else:
print("Thanks!")
break
Try to use "break" in lower case. And, try to put it inside a loop. Please mark my answer if right. The "main" can have loop inside but that is independent of the while loop that I specified at the top.
I think a much simpler code would be something like this...
#set value of again to y. then go into the loop
#again.lower() will convert to lowercase allowing you to check against 'y'
again = 'y'
while again.lower() == 'y' :
main() #this will call main only if again is y
again = input("Would you like to calculate again? y/n")
print("Thanks!") #print thanks after you exit the loop
It seems like you may be coming from C++ where main and break are used. See if this helps. Note, calling a function has to be below/after you have defined it, if you are running python in interactive mode.
# Functions
def main():
print("Start calculator")
def myfunc(again):
if again in ("y", "Y"):
main() # call your calculator
else:
print("Thanks!")
# Run tests
print("Starting Test: 'y'. \n ")
again = 'y' # Set again to 'y'
myfunc(again) # Expect 'Start calculator' output
print("Starting Test: 'Y'. \n ")
again = 'Y' # Set again to 'Y' capital
myfunc(again) # Expect 'Start calculator' output
print("Starting Test: 'n'. \n ")
again = 'n' # Set input to 'n'
myfunc(again) # Expect 'Thanks!' output
print("Starting Test: 'error'. \n ")
again = 'error' # Set input to a random string
myfunc(again) # Expect 'Thanks!' output
Related
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()
I need this program to do one of two things from my repeat function, but it should be able to do both and I can't work out why.
It must do 2 things
make it rerun my main() subprogram,
or say "Goodbye." and close the entire program,
whichever one comes first.
I have tried making it just an if-else statement rather than if-elif-else, which didn't change anything, I have also tried rearranging the code, but that only changes the single output I can get from the subprogram. This is the subprogram currently:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat == 'n' or 'N':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat == 'y' or 'Y':
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
It should be able to repeat the program (based on the y or Y input), terminate the program and display "Goodbye." based on the n or N input or it should display the "Error. Program will shut down." message before closing if an invalid input is entered.
Many thanks to whoever can help me!
You may use in () for the comparison with a list. It compares the value of the variable with the list.
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n): ")
if repeat in ('n','N'):
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ('y','Y'):
main()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
if repeat == 'n' or 'N' doesn't work, since you are checking bool('N') which is always true, the same holds true for repeat == 'y' or 'Y', since
bool('Y') is always true.
You start by checking if repeat is in the list ['n','N'], or is not in the list ['y','Y'], then you exit the program, else you call the same function repeatloop
import time, sys
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/Y/n/N): ")
if repeat in ['n', 'N']:
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat in ['y', 'Y']:
repeatloop()
else:
print("Error. Program will shut down.")
time.sleep(2)
sys.exit()
repeatloop()
Hello and welcome to Stackoverflow.
Your problem is that your if statements are not exactly correct; and also your whole function is not correctly indented.
if repeat == 'n' or 'N' is different from if repeat == 'n' or repeat == 'N'.
In the second case, you test two different statements on the repeat keyword, where on the first one you're seeing whether:
repeat is equal to n, and also
'N' is not None; which isn't & this case always returns true.
Another way to do it could be if repeat in ["n", "N"] or even better: if repeat.lower() == 'n'
So put it all together, your code should be refined to:
def repeatloop():
repeat = input("Do you want to calculate another bill? (y/n):")
if repeat.lower() == 'n':
print("Goodbye.")
time.sleep(2)
sys.exit()
elif repeat.lower() == 'y':
main()
else:
print("Error. Program will shuts down.")
time.sleep(2)
sys.exit()
This question already has answers here:
How can I break out of multiple loops?
(39 answers)
Closed 5 years ago.
Here's a piece of code from my project software:
def fun_1(self, i):
print("")
print("Welcome to Option 1: View Passwords")
while True:
print("")
which_o1 = input("1: Input a New Account details \n2: Exit \nPlease Input the option number: ")
if which_o1 == str(1):
with open(str(i)+'.txt', 'a+') as file:
while True:
print("")
web_n = input("Please Input Website name: ")
print("")
e_u = input("Please input email/username: ")
print("")
pass_w = input("Please input password: ")
while True:
print("")
sure = input("Website- " +web_n+"\nEmail/Username- "+e_u+"\nPassword- "+pass_w+"\nAre You sure about these details? Yes/No: ")
if (sure.lower()[0]) != 'y' and (sure.lower()[0]) != 'n':
print("")
print("Please input a valid response Yes/No!")
continue
elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n':
list_log = [web_n, e_u, pass_w]
file.write(str(list_log) + '\n')
break
break
continue
elif (sure.lower()[0]) == 'n' and (sure.lower()[0]) != 'y':
break
continue
elif which_o1 == str(2):
return (i)
else:
print("")
print("Please Enter a Valid Response!")
continue
So has you can see that it has 3 while True loop. The problem is occurring while breaking and looping the loop. If you see the latest While True under "pass_w" in the middle elif, where it says elif (sure.lower()[0]) == 'y' and (sure.lower()[0]) != 'n':, in it I have 2 break and 1 continue because what I wanted to do is that when that elif executes it just break middle 3rd while true, 2nd while true and continue means loop the first while true at the start of the code, but it just keep looping 3rd While True in the middle of the code instead of breaking it.
Is there a way I can make it possible?
Firstly, understand that no lines can be executed after a break statement inside of a while loop. So putting multiple breaks and a continue won't work. You need to restructure your code. Personally, I would recommend either implementing try except statements, or putting some of the code inside of functions so that you can return when you want to stop looping and pass variables as indications to the outer loops where the function was called.
Another option could be instead of using breaks and continues, use a variable or set of variables that your while loops check for to decide if they should continue. So inside your ifs and elifs you could set exitfirstloop = True, etc. and in the while loops you check while not exitfirstloop
def main():
add_triangle_check = 1
while add_triangle_check > 0:
print "test"
add_triangle()
add_triangle_check= add_triangle()
def add_triangle():
add_triangle_check = 0
user_input = raw_input("Do you want to add more triangles? Y/N")
if user_input == ("y") or user_input == ("Y"):
add_triangle_check = 1
return add_triangle_check
main()
The above code returns the following:
test
Do you want to add more triangles? Y/N
Do you want to add more triangles? Y/N
why is it repeating? I only need the user input once.
You have called function add_traingle() twice.
Remove first add_traingle() and check if it works.
nvm, I thought I had to add the function add_triangle to the while statment so it would repeat properly, by removing it everything is running smoothly
I'm new to python and am taking a class so far my program looks like:
if choice=="1":
def addition():
print("You are doing addition. X+Y=Z")
X = int(input("Enter X:"))
Y = int(input("Enter Y:"))
sum = X + Y
print ("your total is:")
print (sum)
Well = "y"
while Well == "y":
again = input("Would you like to go again? (y/n)")
if again == "y":
addition()
if again == "n":
project()
else:
print("sorry re-enter choice")
it asks if I wan to go again before showing the actual addition part. how do I fix this? Thanks for your help :)
Lots of ways, but you could put your addition() function at the top like this:
Well = "y"
while Well == "y":
addition()
again = input("Would you like to go again? (y/n)")
if again == "n":
project()
if again not in ("n", "y"):
print("sorry re-enter choice")
Just add a flag which changes from false to true on first run, so that you don't see the "again" statement on first run.
A few points:
You shouldn't use sum as a variable name. It is a Python built in.
Look at what variable you use for your loop check, you will notice it quickly.
I think it would make more sense to ask if you want to go again at the end of the loop, after you do your stuff:
while loop_condition:
#do_your_stuff:
bla bla bla
#see if you should go again
bla bla = raw_input("Do you want to go again")
In fact, 99% of the time your while loops will follow this pattern (check condition, run body of loop, update condition) and if you are doing things in a different order (like iupdating the condition before running the body) its usually a sign you might be doing something wrong.