Python while loop not ending when condition is met [duplicate] - python

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...

Related

y/n not working correctly in python code, am unsure why [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I have a y/n query at the end of the game which will restart the game or exit the game.
y and n work as they should, but if I enter any other letter even if it does print the "please try again message", it restarts the game anyway. I thought it should only do that if I put continue, but I haven't
I also want it to recognize y or n as upper case, is there a command in python that allows a letter to be recognized regardless of if its upper or lowercase?
play_again = input('Would you like to play again?(y/n) ')
if play_again == 'y': #loop restarts
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print ("I don't recognize that character, please select y or n")
I have provided the loop as requested, but the last time I did this I got in trouble:
number_of_stones = int(input('Select between 30-50 stones to start your game: ' )) #player1 chooses stones
if number_of_stones >= 30 and number_of_stones <= 50:
print('Starting the game...')
has_winner = False # Winner = False since there no winners (start of game)
while True:
for player in player_list:
if has_winner: # if there is a winner, exit loop
break
# display whose turn is it
print('\n{}\'s turn:'.format(player))
while True:
# if the player is computer use strategy that is mentioned in assignment 2
if player == 'Mr Computer':
remainder = number_of_stones%3
if remainder == 0:
stones_to_remove = 2
else:
stones_to_remove = 1
# if the player is not the computer
else:
stones_to_remove = int(input('Select between 1-3 stones to remove: '))
# assess the number of stones remaining and print the remainder to the screen
if stones_to_remove >= 1 and stones_to_remove <= 3:
number_of_stones -= stones_to_remove
print('Number of stones remaining:',number_of_stones)
if number_of_stones <= 0:
print('The winner is:',player,"!")
has_winner = True
break
else: # show error and let the user input again
print("I'm sorry, that number is outside the range. Please choose a number between 1 and 3")
if has_winner == True: # if the winner=true then exit loop
break
play_again = input('Would you like to play again?(y/n) ').lower() #only accepts lower case letter
if play_again == 'y': #loop restarts
os.system('cls') # clear the console
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print("I'm sorry, that number is outside the range. Please select between 30 and 50 stones.")
You haven't added necessary information ,i.e. rest of the loop , try add that .
For case insensitivity , just use the following
if play_again == "n" || play_again == "N":
.

Why does my code not realize that game = false?

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

Two problems with my code so far.

from random import randint
from time import sleep
fight = False
def start_up():
print("Fight Simulator - Test Stages.")
userInput = str(input("Enter your name "))
user_name = userInput
return user_name
def intro():
userName = start_up()
while True:
userInput = str(input("Welcome to the dojo, {}. To commence the first battle, type 'Start', or 'Begin'".format(userName)))
if userInput == "Start" or "start" or "Begin" or "begin":
return userInput
else:
print("Enter a valid response")
break
def fight_commence():
userInput = intro()
if userInput == "Start" or "start" or "Begin" or "begin":
fight = True
userHp = 100
opponentHp = 100
while fight == True:
userDmg = randint(0,100)
opponentDmg = randint(0,100)
opponentHp -= userDmg
if opponentHp <= 0:
opponentHp == 0
print("You did {} damage".format(userDmg))
sleep(1)
print("Opponent has {} hp remaining".format(opponentHp))
sleep(1)
if opponentHp <= 0:
print("You killed him!")
fight = False
else:
print("Enter a valid action")
fight_commence()
So for some reason the code doesn't print("Enter a valid response") when a response other than "Start" or "start" or "Begin" or "begin" is given. I want it to loop back to userinput stage, but instead it just carries on with the program as if everything is A ok. I can't figure out where I messed up.
Secondly, I want the opponentHp to automatically equal 0 when the health dips below 0. For instance, when opponentHp = -45, opponentHp should equal 0.
Any help is appreciated.
Well a big problem with the testing of the 'valid input' is the way your testing.
if userInput == "Start" or "start" or "Begin" or "begin"
This is not a valid python condition. Instead do something like this:
if userInput in ["Start", "start", "Begin", "begin"]
This comparison happens twice and is no good. For the opponenthp being 0, you currently have this as your statement and result:
if opponentHp <= 0:
opponentHp == 0
The condition is perfectly fine, but the == in the action is another conditional operator, you need to change it to:
if opponentHp <= 0:
opponentHp = 0
ADDITION
Also, in addition to the above items, when you use the break statement you will end the infinite loop you have set up and end the function without a returned value, you may want to consider changing it to a continue or pass statement, or simply remove it.
The conditions (if-clause) are wrong. You should repeat 'userInput==' for every or.
Or, more concisely this:
userInput.lower() in ["start", "begin"]

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

How to restart a simple coin tossing game

I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.

Categories