Can I create a function to break a while loops in python? - python

I am writing a program with python to simulate flipping a coin or rolling dice. The coin and dice use while loops to give the user the option to roll or flip again, an example is:
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
done = input("""would you like to roll again? Type y to roll again,
type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The problem I am having is that I would like to take every line starting from done and make it into it's own function that I can just insert into every function rather than typing the whole thing out again and again, like this.
def d4ing():
d4ing = True
while d4ing:
print(random.randint(1,4))
rerolling()
def rerolling():
done = input("""would you like to roll again? Type y to roll again, type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The error message I am getting:
SyntaxError: 'continue' not properly in loop

A break or a continue must be in a loop in its current scope. You cannot break a loop in the above scope from inside a function. Here is a general example of what raises the SyntaxError: 'break' outside loop error. The same holds for continue.
def break_up():
break # This is a syntax error
while True:
break_up()
Although, this is not a problem, since you can make the function return a value and conditionally break in the upper scope.
In your specific example though, you can also return whether or not you want to reroll by assigning the return value to d4ing.
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
d4ing = rerolling()
def rerolling():
done = input("Would you like to roll again?")
if done == "y":
return True
elif done == "d":
return False
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")

Related

Control flow - Jump to another loop?

I did not find any duplicates of this question, i understand that Python has no "goto" functionality in itself and how i can make use of "continue" in a loop to get the same effect, but i'm not really sure if it's any recommended method of "jumping back" to another loop for eg? Let me show you an example below
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
pass
# Here i would want to be able to send the user back to the 1st loop if user gives any other input than "yes" or "no"
The only thing i can think of right now that makes any sense (to not have to simply rewrite the whole thing again) is to simply set the first loop to a function and call that from the second loop to get the result i want, this works as i intend it to:
def firstloop():
while True:
print("Hey! Some text.. blablah")
x = input("You wanna continue? (yes/no) ")
if x == "yes":
continue
else:
print("End of loop")
break
firstloop()
while True:
print("Hey! Some more text, blablah even more")
x = input("You wanna continue? (yes/no): ")
if x == "yes":
continue
elif x == "no":
print("End of program")
break
else:
firstloop()
But somehow it feels like i'm over complicating something, or is this the "best" way i can go by with something like this? Thanks
You should put the second loop inside the first one (or inside an enclosing while for both). GOTOs are never needed, See here: https://en.wikipedia.org/wiki/Structured_programming

What could be causing my program to go over a function twice even though it should be exiting after running over it once?

I am trying to make a game of rock, paper, scissors, and I am having issues figuring out why my program is reiterating over a function twice when it it supposed to go over it once and then start back at the beginning due to a while loop.
Here is the function that is causing the problem (unnecessary information filtered out):
def playRps(): # Compares the choices and determines who won the game
game = "".join([playerAction, computerAction])
outcomes = {
"rr": tied,
"pp": tied,
"ss": tied,
"rp": playerLoss,
"ps": playerLoss,
"sr": playerLoss,
"rs": playerWin,
"pr": playerWin,
"sp": playerWin,
}
if playerAction == "q":
return False
else:
action = outcomes.get(game)
if action:
action()
else:
print("Invalid input!")
You can find the entire functions.py file here.
Here is the main.py file that calls the functions and runs the program (unnecessary information filtered out):
while True:
if functions.playerScore != 0 or functions.computerScore != 0:
functions.scores()
playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))
if playGame == "y":
while True:
functions.playerChoice()
functions.computerChoice()
functions.playRps()
if not functions.playRps():
break
elif playGame == "n":
print("Terminating program...")
quit()
else:
print("Unknown input. Please enter a valid answer.")
continue
You can find the entire main.py file here.
Well, the program appears to go to actions = outcome.get(game) in functions.py as expected when you don't input q. Then, it goes to the main.py file and validates the outcome at if not functions.playRps():.
For some reason, it then proceeds to go back to functions.py and it ends up back at actions = outcome.get(game), which adds a second point. Then it goes back to main.py and then it hits the break right after the if not functions.playRps():.
It shouldn't be hitting be repeating playRps() twice, nor should it be hitting the break in main.py when I didn't input q as the player response. It should go back to the playerChoice() function in main.py due to the while loop, so the player could make their choice.
The while loop in main.py shouldn't be broken at all unless the player enters q when the playerChoice() function is called.
My question to you guys is:
Why is the program repeating the playRps() function twice, and why is the while loop in main.py where the functions are called being broken even though the player never entered q when the playerChoice() function is called?
The function is being called the second time because you call the function again in your if statement:
functions.playRps() # call 1
if not functions.playRps(): # call 2
break
You should set a variable to the result of that function so that you can evaluate it in the if statement without calling it again:
result = functions.playRps()
if not result:
break

Programming an atm machine

My assignment is to create an ATM-type program. Below is my main function (not including the deposit, withdraw, and check balance functions). When I go to run this code, the program loops the pin function repeatedly, even when I enter 0 or 1234. It repeatedly instructs the user to enter their pin. I think I have all of the indentation right, but I guess I'm messing up somewhere in the code.
def main():
pin_number = input("Please enter your pin number")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop == True
if pin_number == "1234":
stop == False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
In your if statements, you should be using = not ==. The first is used for assigning values to variables, like you are trying to do. The second is used to compare if two values are equal and returns a boolean (true/false).
Your code
if stop != True:
will run the code inside the loop if the variable stop is False (the user has entered the wrong code). However, you want to run the code if stop is True.
Therefore, use this code:
if stop == True:
this will run the encased code when stop is True (user has entered correct code)
EDIT:
My apologies. The above answer regards the code following this code:
if pin_number == "1234":
stop = False

is a While True or If Statement best to execute one function before moving to the next

I am stuck on a simple issue. I am attempting to ask the user to choose a desired function from a list. This inputted user string will invoke the chosen function until it finishes running. (It is a lighting sequence). After this sequence ends, I would like to ask the user if he or she wishes to choose another function. If so, continue. If not, exit the code.
I cannot decide if a while true or if statement is the best to achieve this.
Here is my code:
# random functions
def rainbow():
print 'rainbow'
def clover():
print 'clover'
def foo():
print 'eggs'
if __name__ == '__main__':
# here are some random initializations
print 'ctr-c to quit'
user_input = input("choose from the following: ")
if user_input == 'rainbow':
print 'generating'
rainbow()
rainbow()
rainbow()
user_input = input('choose another')
if user_input == 'foo':
clover()
clover()
I would suggest using a while loop here until you get a successful user_input, upon which you'll want to break the loop. Inside the while look you can have your if statements as needed. For example, in your above code, what happens if the user types in "rainboww", it basically just exits the program. It'd be better to have it like this:
while True:
user_input = input('...')
if "good result"
break
else:
continue
while True:
user_input = input("choose from the following: ")
if user_input == "condition a":
do something
elif user_input == "condition b":
do something..
elif any(user_input == keyword for keyword in ["q", "quit"]):
# when meet any quit keyword, use break to terminate the loop
break
else:
# when doesn't find any match, use continue to skip rest statement and goto the beginning of the loop again
continue
while True can meet your requirement. you can use if-elif-else clauses to do different works.

Looping error (homework)

I'm having an issue with (apparently) a loop not working as intended. Assuming that everything else works as intended, my second while loop is (according to the grader) calling raw_input more times than necessary.
The code plays a word game. You can play a hand, replay a hand, or exit. Second loop determines if you play the hand or the computer.
All the called functions work correctly, but the loop, as I said is calling raw_input too many times.
Sorry if there are lots of other issues, I'm relatively new to coding.
userInput = ''
playInput = ''
hasPlayed = False
# while still playing, e exits
while userInput != 'e':
userInput = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ").lower()
if userInput not in 'nre':
print("Invalid command.")
elif userInput == 'r' and hasPlayed == False:
print("You have not played a hand yet. Please play a new hand first!")
print
else:
while True:
#
print
playInput = raw_input("Enter u to have yourself play, c to have the computer play: ").lower()
if playInput == 'u':
print
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
hasPlayed = True
elif playInput == 'c':
print
hand = dealHand(HAND_SIZE)
compPlayHand(hand, wordList, HAND_SIZE)
hasPlayed = True
else:
print("Invalid command.")
print
Your loop is working perfectly fine; it is looping forever just like you told it to:
while True:
What is missing then, is a way to exit that loop. Either test for a different condition:
playing = True
while playing:
# game
#
# stop playing with
playing = False
or explicitly break out of the loop with the break keyword:
while True:
# game
#
# stop playing with
break

Categories