Enter blank value in try statements - python

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.

Related

Turn/chance feature in following code is not working

I am trying to create a IPL/Fanstasy cricket simulators in which you create your team and play. You auction the players. In the auction function, I have added a turn feature, which means if the turn variable is even, then its your turn, if its odd, then its other bidders turn.
def auction(money, turn, choice):
if turn % 2 == 0:
while True:
print("It is your turn to choose a player.")
while True:
selected_player = str(
input("Enter the name of the player you wish to choose(leave empty to skip):"))
if selected_player in players:
break
elif selected_player == "":
print("Turn Skipped")
else:
print("That player is not in your players")
selected_player_bid = int(input("Enter the amount of money for which you wish to buy the player(leave "
"empty to skip):"))
if selected_player_bid > money:
print("You dont have enough money to buy the player.")
else:
your_players.append(selected_player)
print("Player bought")
break
break
else:
selected_player = random.choice(players)
selected_player_bid = random.randint(1, 100000)
print(
f"{random.choice(bidders)} chooses {selected_player} for {selected_player_bid}.")
print(
"You can either type [p]ass let them take the player or type [c]hallenge to challenge them.")
while True:
choice = input("Challenge or pass: ")
if choice.lower() == "challenge":
break
elif choice.lower() == "pass":
break
elif choice.lower() == "p":
break
elif choice.lower() == "c":
break
else:
print("Not a valid command, please type again.")
while choice.lower() == "challenge" or choice.lower() == 'c':
bid = int(input("Enter your bid: "))
if bid > money:
print("You do not have enough money.")
elif bid < selected_player_bid:
print("That is lower than the starting bid.")
else:
print(f"{selected_player} bought for {bid}")
money = money - bid
print("You have enough money.")
your_players.append(selected_player)
break
if choice.lower() == "p" or choice.lower() == "pass":
pass
players.remove(selected_player)
The usage of the function(This is where I was trying to fix the code).
while True:
if random_choice:
turn = turn + 1
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
else:
random_choice = bool(random.choice(binary_numbers))
auction(your_money, turn, choice)
pass
if len(players) == 0:
break
else:
continue
GitHub repo
You can comment the fix or create a pull request.
Thanking you in advance.
I expected the code to randomly choose the bidder, either the player or the bots, but when I was fixing it, it was not doing so.

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.

How can I get two variables to hold the amount of higher than and lower than guesses?

I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.

fruit machine GSCE challenge

I'm sure you have all heard of the GCSE fruit machine challenge. Well I am having issues with that, you see, when the user spins 3 skulls it doesn't deduct all their credits and when they only spin 2 skulls it doesn't deduct 1 credit. If anyone can help please do.
credit = 1
import time
t = 1
while True:
import random
symbols = 'Star' , 'Skull'
spin = random.choices(symbols,k=1)
spin2 = random.choices(symbols,k=1)
spin3 = random.choices(symbols,k=1)
ask = input('do you want to spin? ')
if ask == 'yes':
credit = (credit - 0.2)
credit = (round(credit, 2))
print('You now have... ' +str(credit) + ' credit(s).')
time.sleep (t)
print('** NOW ROLLING **')
time.sleep (t)
print('You rolled... ' +str(spin) +str(spin2) +str(spin3))
time.sleep (t)
if (spin == spin2 == 'Skull' or spin == spin3 == 'Skull' or spin2 == spin3 == 'Skull'):
credit = (credit - 1)
credit = (round(credit, 2))
print('Uh Oh! you rolled 2 skulls.... you lost 1 credit sorry!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == 'Skull' and spin2 == 'Skull' and spin3 == 'Skull':
credit = (credit - credit)
print('You rolled 3 Skulls!! You lost all your credits!')
break
elif spin == spin2 and spin2 == spin3:
credit = (credit + 1)
print('You won 1 credit!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif spin == spin2 or spin == spin3 or spin2 == spin3:
credit = (credit + 0.5)
credit = (round(credit, 2))
print('You won 0.5 credits!')
print('You now have a total balance of... ' +str(credit)+ ' credits!')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
else:
print('Sorry you didnt win anything.')
if credit >= 0.2:
continue
else:
print('Sorry! you dont have enough credits.')
break
elif ask == 'no':
print('Your total winnings are.... ' +str(credit))
break
else:
print('please say yes or no..')
continue
The problem is you are comparing list to string where "Skull" is a string and the variable "spin" is a list of one element. To solve this you can turn "spin" to a string using spin = random.choice(symbols) which will make one choice as a string.
You seem new to python so I also rewrote your code. You are more than welcome to ask questions about it :)
import time
import random
t = 1
credit = 1.0
while True:
symbols = "Star", "Skull"
spins = random.choices(symbols, k=3)
ask = input("Do you want to spin? ")
if ask == "yes":
credit -= 0.2
print(f"You now have... {credit} credit(s).")
time.sleep(t)
print("** NOW ROLLING **")
time.sleep(t)
print("You rolled... " + " ".join(spins))
time.sleep(t)
if sum(spin == "Skull" for spin in spins) == 2:
credit -= 1
print("Uh Oh! you rolled 2 skulls.... you lost 1 credit, sorry!")
elif sum([spin == "Skull" for spin in spins]) == 3:
credit = 0
print("You rolled 3 Skulls!! You lost all your credits!")
elif all(spin == spins[0] for spin in spins):
credit += 1
print("You won 1 credit!")
elif len(set(spins)) != len(spins):
credit += 0.5
print("You won 0.5 credits!")
else:
print("Sorry you didn't win anything.")
credit = (round(credit, 2))
print(f"You now have a total balance of... {credit} credits!")
if credit >= 0.2:
continue
else:
print("Sorry! You don't have enough credits.")
break
elif ask == "no":
print(f"Your total winnings are.... {credit}")
break
else:
print("Please say yes or no..")
continue
Good Luck

Break out of Python loop, without break

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.

Categories