I have a while loop that says:
game = True
while game == True:
shop = False
while shop == False:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/#WeirdDragon/ore-digging-sim#main.py
You need to break out of the inner loop so you can get back to the outer loop's test.
game = True
while game:
shop = False
while not shop:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
break
You need shop == True to break from the inner while first. Then, it can realize that game == False
You need to understand how while loops work, take this for example:
a = 5
while a == 5:
a = 6
print('done')
Output:
done
The condition we gave the while loop tells it when to stop looping, but python must first reach the condition again in order to compare, meaning as long as there is no break statement, python will first finish the current loop. But in your code, because of the other while loop in that while loop never ends, we never gave python a chace to compare that game condition.
game = True
while game == True:
shop = False
while shop == False:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
To fix that, simply add a break statement after the game = False:
if choice == "E" or choice == "e":
game = False
break
Related
This question already has answers here:
Why doesn't the while loop stop when the condition becomes False?
(3 answers)
Closed last month.
I'm assuming the issue has to be with setting a global variable but even with my trying to fix it with that, I still can't seem to figure it out. Code is pretty rough but I only started learning <2 days ago so please bear with me. From my understanding, if the password is entered correctly, the game variable should be equal to False which should end the loop. However, it keeps going on and asking player 1 for input. Also, I can't seem to be getting the checkGame function to work properly inside the while loop.
board = [
0,1,2,
3,4,5,
6,7,8
]
print(board)
global counter
counter = 0
global game
game = True
def checkGame():
if board[0] == player_1:
print("Game won by player 1!")
game == False
def player_1():
player_1 = 'X'
# return player_1
selection = int(input("P1: Pick a position: "))
board[selection] = player_1
print(board)
global game
global counter
counter += 1
print("Counter = ", counter)
print("game:", game)
def player_2():
player_2 = "O"
selection = int(input("P2: Pick a position: "))
board[selection] = player_2
print(board)
global counter
counter += 1
print("Counter = ", counter)
print("game:", game)
while game == True:
password = input("password: ")
if password == 'testing':
game = False
print(game)
else:
pass
if counter == 9:
game = False
player_1()
if board[0] == player_1:
print("Game won by player 1!")
game == False
if counter == 9:
game == False
checkGame()
player_2()
if counter == 9:
game == False
checkGame()
A while loop's condition is not checked continuously, only at the start of each loop iteration. To exit the loop immediately use a break statement. For example, in this code it will print "Keep running" even after you type "exit"
running = True
while running:
password = input("password: ")
if password == "exit":
running = False # does not exit the loop, just stops the next run
print("Keep running")
but in this code it will not
running = True
while running:
password = input("password: ")
if password == "exit":
break # exits the loop
print("Keep running")
Also, unrelated to your immediate issue of not exiting on the password entry, var == False does not set var to false, it just checks if it is equal to false. Be sure to use = for assignment, not ==.
You also seem to be mixing method names and variable names (e.g. player_1) which is probably going to cause problems...
I've tried googling and searching on SO, but I cant figure out why my break on the second to last line is not heading out of the while loop. Better yet, I cant figure out why the loop is not continuing either. My intention is to give the user the possibiltiy to head to the main menu after the last choice (basically the while loop for menuchoice (which is one loop above what I have pasted here).
Any suggestions? Thank you in advance. It feels like I'm missing something essential.
#this is going to show how many exercise weapons you need for next magic level
if menuchoice == "4":
#these functions returns the amount of magic wands/rods that is needed to be spent for next magic level
print("Select vocation")
print("Press P for Royal Paladin")
#ask user to input vocation:
while True:
vocationchoice = input()
if vocationchoice == "P" or vocationchoice == "p":
#ask user to input magic level for paladin
num1 = float (input("Enter your magic level: "))
#ask for own training dummy
print("Do you have your own exercise dummy? Type Y for yes and N for no.")
while True:
trainingdummy = input()
if trainingdummy == "y" or trainingdummy == "Y":
#list the different exercise weapons
print("Select exercise weapon:")
print("1. Training rod")
#loop, where we ask user to input what exercise weapon they want to calculate
while True:
while True:
weaponchoice = input()
if weaponchoice == "q":
sys.exit() #quit the program
if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
break #break out of the input loop
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
if trainingdummy == "n" or trainingdummy == "N":
#list the different exercise weapons
print("Select exercise weapon:")
print("1. Training rod")
#loop where ask user to input what exercise weapon they want to calculate
while True:
weaponchoice = input()
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpal(num1))) + ".")
elif weaponchoice == "f":
break
print("\nGo to main menu? Press F.")
This will help you I think. Break only breaks from current loop. If you want to go up on levels you need to break from each loop separately.
A suggestion is to turn a loop into a function and use return which will effectively exit any loop. A little bit of code refactor will be needed though.
If not the case can you maybe provide some more info and possibly the full code (there is a higher loop that we dont see here?)
First, you should print things in the input() command as it will be cleared in intend: input("Text to display").
Second, if you want to exit to the main menu, you need to break every nested loop. Here you only break the most inner loop.
As in Python there is no goto instruction nor named loops, you can use a flag. A flag is set to true when the used presses 'F' and this flag is then used at the beginning of every outer nested loop to break them. It can look like this:
while True: # This is your menu loop
menuFlag = False # Declare and set the flag to False here
menu = input("Choose the menu: ")
# ...
while True: # Choose character loop
if menuFlag: break # Do not forget to break all outer loops
character = input("Choose a character: ")
# ...
while True: # Any other loop (choose weapon, ...)
weapon = input("Choose weapon: ")
# Here you want to return to the menu if f is pressed
# Set the flag to True in this condition
if weapon == "f":
menuFlag = True
break
In your game this ressembles to:
goToMainMenu = False
while True:
if goToMainMenu: break
vocationchoice = input("Select vocation.\nPress P for Royal Paladin: ")
if vocationchoice == "P" or vocationchoice == "p":
#ask user to input magic level for paladin
num1 = float (input("Enter your magic level: "))
#ask for own training dummy
while True:
if goToMainMenu: break
trainingdummy = input("Do you have your own exercise dummy?\nType Y for yes and N for no: ")
if trainingdummy == "y" or trainingdummy == "Y":
#loop, where we ask user to input what exercise weapon they want to calculate
while True:
while True:
weaponchoice = input("Select exercise weapon:\n1. Training rod: ")
if weaponchoice == "q":
sys.exit() #quit the program
if weaponchoice == "1" or weaponchoice == "2" or weaponchoice == "3" or weaponchoice == "f":
break #break out of the input loop
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
if trainingdummy == "n" or trainingdummy == "N":
#list the different exercise weapon
#loop where ask user to input what exercise weapon they want to calculate
while True:
weaponchoice = input("Select exercise weapon (press F for main menu):\n1. Training rod: ")
#User choice
if weaponchoice == "1":
print("The amount of training rods needed for next magic level is " + str((nextmaglvlpalwithdummy(num1))) + ".")
elif weaponchoice == "f" or weaponchoice == "F":
goToMainMenu = True
break
Add a break for weaponchoice == "1" to get out of the loop.
I'm creating a dice poker game and am trying to ask if the user would like to play before continuing with the game and then asking if the player would like to play again after each game.
I am unsure how to allow for incorrect inputs other than Y and N in order to tell the user to enter a correct answer and then loop the input until either is input. I am not allowed to use a break.
play = True
s = input("Would you like to play dice poker [y|n]? ")
if s == "y":
play = True
elif s == "n":
play = False
else:
print("Please enter y or n")
while play:
From here onward is the code for my game
This below section is repeated at the end of each game
again=str(input('Play again [y|n]? '))
if again == "n":
play = False
if again == "y":
play = True
else:
print('Please enter y or n')
wrap your input in a function that evaluates the user input, if it's not valid, call it recursively as necessary. Example:
def keep_playing():
valid = 'ny'
again=str(input('Play again [y|n]? '))
a = again.lower().strip() # allow for upper-case input or even whole words like 'Yes' or 'no'
a = a[0] if a else ''
if a and a in valid:
# take advantage of the truthiness of the index:
# 0 is Falsy, 1 is Truthy
return valid.index(a)
# Otherwise, inform the player of their mistake
print(f'{again} is not a valid response. Please enter either [y|n].')
# Prompt again, recursively
return keep_playing()
while keep_playing():
print('\tstill playing...')
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")
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