Break out of Python loop, without break - python

In the below code, why doesn't it stop looping when fighting is set to False?
I know it does not stop looping, because it won't get to the loot part when fighting is set to False. Here is the whole while loop:
while fighting:
cls()
print("The enemy has", opponent.HP, "HP!")
input()
if int(opponent.HP) <= 0:
print("Yep yep")
winner = True
fighting = False
elif int(ownedCreatures[activeCreature].HP) <= 0:
winner = False
fighting = False
showFight(opponent, activeCreature)
allowed = ["a", "i", "r"]
choice = input(">>")
while not choice in allowed:
choice = input("Try again please >>")
if choice.lower() == "a":
if previousTurn == "Not defined":
num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
if num <= ownedCreatures[activeCreature].support:
attacker = "player"
previousTurn = "player"
else:
attacker = "opponent"
previousTurn = "opponent"
else:
if previousTurn == "player":
attacker = "opponent"
previousTurn = "opponent"
else:
attacker = "player"
previousTurn = "player"
attack(attacker, activeCreature, opponent)
#if choice.lower() == "i":
if choice.lower() == "r":
num = random.randint(1, ownedCreatures[activeCreature].support + opponent.support)
if num <= ownedCreatures[activeCreature].support:
cls()
print("-------------------------------------------")
print("You succesfully escaped this horrible fight!")
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")
winner = "Not defined"
fighting = False
else:
cls()
print("-------------------------------------------")
print("Think you can run that easily?")
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")
#After the fight
if winner == True:
cls()
loot()
elif winner == False:
cls()
print("-------------------------------------------")
print("You have lost the fight!")
print("You lost 50 Serra!")
serra = serra - 50
if serra < 0:
serra = 0
print("-------------------------------------------\n")
input("Press Enter to continue... >> ")

You have three places inside the loop where you set fighting to False and all of them coming with an if condition:
int(opponent.HP) <= 0
int(ownedCreatures[activeCreature].HP) <= 0
num <= ownedCreatures[activeCreature].support
The first and the second conditions are constant inside the loop, so if they start False, the change of fighting will never be accessible.
The third: num is a random number greater than 1 so if ownedCreatures[activeCreature].support is 0, the condition will never be accessible.
Print the values of conditions to check if they are fulfilled or not.

Related

Python -- 3 dices game question by using while loop

I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass

Boolean does not control while loop for me

All of this code does not get affected by a SIGKILL command and my while loop continues no matter what condition
Code:
if Play == False:
signal.SIGKILL(0)
if gameplayint == "N":
print("What are you doing here then?")
Play == False
if gameplayint == "Y":
Play == True
time.sleep(0.5)
print("We will start now.")
#Start the game.
print("")
#Actual gameplay block of code
#game start
while Play == True:
pcNum = random.randint(1,19)
anotherNum = True
total = 0
while anotherNum == True:
playerNum = random.randint(1,10)
total = total + playerNum
print("")
print("Your number is ", str(playerNum) + ".")
print("You have " + str(total) + " in total.")
print("")
again = input("Roll another number? <Y or N> ")
print("")
if again == "Y":
anotherNum = True
else:
anotherNum = False
break
#game finished now
print("Computer got", pcNum)
print("You got", total)
#checking for winner
while anotherNum == False:
if (total <= 13) and (total > pcNum):
print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
print("The computer has bested you,", name + "!")
else:
if (total == pcNum) and (total <= 13):
print("Draw...")
elif (pcNum > 13) and (total <= 13):
print("You,", name + " have won!")
else:
print("Both of you have lost. Wow...")
again = input("Try again? <Y or N>")
if again == "Y":
Play = True
else:
Play = False
print("Goodbye now.")
Output:
What's your name? Y
Very well then Y, do you want to play 13? <Y or N> N
What are you doing here then?
Your number is 3.
You have 3 in total.
The issue here is that despite N being outputted on the gameplayint variable, the while loop still continues instead of stopping the output entirely.

Enter blank value in try statements

I am making a blackjack game for school and for this part, the user can choose their bet. It can be 0 to quit, press enter to keep the previous bet, or type a new bet. I got the enter 0 part, but I think my ValueError is blocking the user from entering a blank value. I apologize for the messy code. Is there another except statement I could add in to allow some mistakes, or do i need to restructure the entire loop?
import random
import sys
def main():
restart = True
bank_balance = 1000
player_name = input("Please enter your name: ")
while (restart):
print (f"Welcome {player_name}, your bank balance is ${bank_balance} ")
correct = False
user_bet=0
bet = input_bet(user_bet, bank_balance)
if (user_bet == 0):
print('Quiting the game')
break
win_lose = play_hand(player_name, bet)
bank_balance+=win_lose
print(f'Your bank balance: ${bank_balance}')
play=bet
def input_bet(bet, money):
correct = False
while not correct:
try:
enough_money = False
while not enough_money:
bet=int(input("Bet? (0 to quit, press 'Enter' to stay at $25) "))
if (bet > money):
print('not enough money')
elif (bet == 0):
return 0
elif (bet <= money):
print(f'Betting ${bet}')
enough_money=True
return bet
correct = True
except ValueError:
print('Please enter a number')
def play_hand(name, bet):
player= []
dealer= []
play_again = True
dealer.append(random.randint(1, 11))
player.extend([random.randint(1, 11), random.randint(1, 11)])
print ('The dealer received card of value', *dealer)
print(name, 'received cards of value', player[0], 'and', player[-1])
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s total is {sum(player)}", '\n')
stay = False
bust = False
while (sum(player) <= 21 and stay == False and play_again == True):
hors= input(f"Type 'h' to hit and 's' to stay ")
if (hors == 'h'):
new_card= random.randint(1, 11)
player.append(new_card)
print(f'{name} pulled a {new_card}')
print(f'Dealer total is {sum(dealer)}')
print(f"{name}'s cards are", *player)
print(f"{name}'s total is {sum(player)}", '\n')
elif (hors == 's'):
stay=True
print('stay')
if (sum(player) > 21 ):
bust = True
print('You busted!')
return -bet
while (stay == True and sum(dealer) < 17 and bust == False and play_again == True):
dealer.append(random.randint(1, 11))
print('The dealers cards are', *dealer)
print('The dealers total is', sum(dealer), '\n')
if (sum(dealer) <= 21 and sum(dealer) > sum(player)):
print("The dealer wins!")
return -bet
elif (sum(player) <= 21 and sum(player) > sum(dealer)):
print("You win!")
return bet
if (sum(dealer) > 21):
print ('You win! The dealer busted!')
return bet
if (sum(dealer) == sum(player)):
print('Its a Tie! ')
return 0
main()
The immediate issue is that int("") raises a ValueError, rather than returning 0 like int() does. The solution is to check the return value of input before you attempt to produce an int.
def input_bet(money):
while True:
response = input("Bet? (0 to quite, press 'Enter' to stay at $25) ")
if bet == "0":
return 0
if bet == "":
bet = "25"
try:
bet = int(bet)
except ValueError:
print("Please enter a number")
continue
if bet > money:
print("Not enough money")
continue
return bet
The only parameter input_bet needs is the player's total amount, to prevent betting more than is available. No initial bet is needed.

Program exits when players number of turns = 6. Python Battleship Game

I'm making a 2-player battleship game in python. I've made it so that each 'game' allows a total of 6 turns (3 from each player), after which a message will appear saying 'The number of turns has ended'.
Once this happens, they will be asked to play again. If they answer 'yes' or 'y', the game should reload. However it doesn't. The board loads but the program then exits. I believe the issue lies with my play_again() function but I'm not quite sure what it is.
I want to make it so that the players can play as many games as they want until they decide to answer 'no' or 'n'. How do I go about implementing this?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
}
player_two = {
"name": "Player 2",
"wins": 0,
}
colors = {"reset":"\033[00m",
"red":"\033[91m",
"blue":"\033[94m",
"cyan":"\033[96m"
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("Find and sink the ship!")
del board[:]
build_game_board(board)
print(colors['blue'])
show_board(board)
print(colors['reset'])
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
return player_two
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
break
elif answer in negative:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"
print(colors['cyan'])
show_board(game_board)
print(colors['reset'])
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for turns in range(6):
if player_turns(turns) == player_one:
print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The number of turns has ended.")
print(colors['red'])
show_board(game_board)
print(colors['reset'])
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
play_again()
if __name__ == "__main__":
main()
It also worked for me when I added an invocation to main in your play_again() function:
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
main()
break
elif answer in negative:
print("Thanks for playing!")
exit()
Try modifying main with:
turns = 0
while turns < 6:
# Process turn...
if turns == 5:
# Show endgame board
if play_again():
turns = -1
turns += 1
And have play_again return True on positive input ['y', 'yes'] and False otherwise.
The problem is that your play_again() call, upon receiving "Y" as answer, loads the board, but then simply returns. Where? Well, to the place it was called from - the for loop in main(). And unfortunately, it is the last iteration of said for loop, so the loop then ends and the program exits.
You should've put another loop around the for loop:
while True:
for turns in range(6):
...

Beginner Python-Looping to the beginning of a programme

I will start fresh! I have included the full code so you can get a picture for what i am trying to do. Prob (1) I can not loop back to the very beginning. Prob (2) It is not looping # the While higher_or_lower part of the code. it just goes through the if and else higher_or_lower statements. Thanks
done = False
while done == False:
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess)
input("Correct!\nWell done\n\n")
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the number game. Goodbye")
done = True
breaK
Ok, a primer in how Python indentation works.
number = 1
while number < 10:
print(number)
number += 1
print("this will print everytime because it's inside the while")
Output:
1
this will print everytime because it's inside the while
2
this will print everytime because it's inside the while
3
this will print everytime because it's inside the while
4
this will print everytime because it's inside the while
5
this will print everytime because it's inside the while
6
this will print everytime because it's inside the while
7
this will print everytime because it's inside the while
8
this will print everytime because it's inside the while
9
this will print everytime because it's inside the while
Notice that the second print prints every time because of it's indentation.
Now the second example:
number = 1
while number < 10:
print(number)
number += 1
print("this will print AFTER the loop ends")
Output:
1
2
3
4
5
6
7
8
9
this will print AFTER the loop ends
See how it only printed after the loop ended? That is because of the indentation. You should correct your code and indent it properly...
Ok, I corrected the code and it seems to be working now. Most of it was because of the indentation. Please try to understand how it works...
import random
def is_same(targ, num):
if targ == num:
result="WIN"
elif targ > num:
result="LOW"
else:
result="HIGH"
return result #this was out indented
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print( """\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""" )
Choose_Level = input("\t\tPlease choose your Level : " )
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
Choose_Level = input("Sorry. You must type in one of the letters 'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! You are a guessing number warrior")
if Choose_Level == "E":
computer_number = random.randint(1,10)
elif Choose_Level == "M":
computer_number = random.randint(1,50)
else:
computer_number = random.randint(1,100)
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter = 1
while higher_or_lower != "WIN":
counter +=1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
guess = int(input("\nSorry, you are to low. Please try again.\n:"))
else:
print("Guess attempts", counter)
guess = int(input("\nSorry, To high. Please try again. \n:"))
higher_or_lower = is_same(computer_number, guess) # this was out indented
print("Correct!\nWell done\n\n") # this all the way to the bottom was out indented
print( """
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = (input("\t\t Please choose a option 'S' or 'E' "))
while start_again != "S" and start_again != "E":
start_again = (input("You must enter a upper case letter 'S' or 'E' to continue"))
if start_again == "S":
done = False
else:
print("Thanks for playing the awesome number game. Goodbye")
done = True
It looks like adding a little structure would help you out.
Something like this might help you with doing your control flow. Hopefully gives you an outline that makes sense and makes it easier to run the loop multiple times.
""" Guess the number game.
"""
import random
def is_same(targ, num):
""" Check for correct entry. """
if targ == num:
result = "WIN"
elif targ > num:
result = "LOW"
else:
result = "HIGH"
return result
def play_game():
""" Play the game 1 time, returns play_again """
User_Name = input("What is your name?\n:")
print("\nWelcome", User_Name, "To the guessing number game")
print("""\n\n
GUESSING NUMBER GAME
----------------------------------
##################################
# #
# [E] For Easy 1 - 10 #
# #
# [M] For Medium 1 - 50 #
# #
# [H] For Hard 1 - 100 #
# #
##################################
""")
Choose_Level = input("\t\tPlease choose your Level : ")
while Choose_Level != "E" and Choose_Level != "M" and Choose_Level != "H":
# this could be simplified to: while choose_level not in 'EMF':
Choose_Level = input("Sorry. You must type in one of the letters " +
"'E', 'M', 'H'\n:")
if Choose_Level == "E":
print("You have chosen the Easy Level! You are a wimp by nature")
elif Choose_Level == "M":
print("You have chosen the Medium Level! Can you defeat the game?")
else:
print("You have chosen the Hard Level! " +
"You are a Guessing Number warrior")
if Choose_Level == "E":
computer_number = random.randint(1, 10)
elif Choose_Level == "M":
computer_number = random.randint(1, 50)
else:
computer_number = random.randint(1, 100)
counter = 1
higher_or_lower = ""
while higher_or_lower != "WIN":
guess = int(input("Can you guess the number? \n:"))
higher_or_lower = is_same(computer_number, guess)
counter += 1
if higher_or_lower == "LOW":
print("Guess attempts", counter)
print("\nSorry, you are to low. Please try again.\n:")
elif higher_or_lower == "HIGH":
print("Guess attempts", counter)
print("\nSorry, To high. Please try again. \n:")
else:
print("Correct!\nWell done\n\n")
break
print("""
##############################
# #
# [S] Play again #
# #
# [E] Exit #
# #
##############################
""")
start_again = input("\t\t Please choose a option 'S' or 'E' ")
while start_again != "S" and start_again != "E":
# can simplify: while start_again not in 'SE':
start_again = input("You must enter a upper case letter" +
"'S' or 'E' to continue")
if start_again == "S":
return True
else:
return False
def main():
""" Main loop for playing the game. """
play_again = True
while play_again:
play_again = play_game()
print("Thanks for playing the number game. Goodbye")
if __name__ == '__main__':
main()

Categories