Loop continues looping, even after termination message - python

I am having some trouble with getting user input to stop looping after the termination message. Basically, once 0 (zero) is entered in the Enter bet field, the program must print a termination message and end. However, it continues to loop by asking for the next line of input "Choose a number between 2 and 12" when it should be skipped.
I know a break or exit() will fix my problem, but those are not acceptable solutions. Once 0 (zero) is entered in the Enter bet field, I need it to finalize and print a termination messag. Not continue on with the program.
Example NEEDED output:
you have $500 in your bank # starting amount
Enter bet (or 0 to quit): 0
Thanks for playing!
What I am getting instead:
Enter bet (or 0 to quit): 0
Thanks for playing!
Choose a number between 2 and 12: # where the program continues to run
# when it shouldn't. The user should only see this input field if they enter
# number above 0
This is the code
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
bet = int(get_bet)
if get_bet == '0':
print('Thanks for playing!')
return bank, bet
return bank, bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
prog_info()
bank = 500
guess = get_guess
rcnt = 1
while rcnt < 4:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet
if bank == 0:
print(f'You have ${bank} in your bank.')
print('Thanks for playing!')
Create a “bank” (variable) with a starting value of $500.
Ask the player for a bet
Must be 0 (zero) or greater and cannot exceed the amount currently in the bank.
Roll the 2 die
If the players guess matched the 1st roll then add double the amount bet to the “bank”
If the players guess matched the 2nd roll then add 1 ½ times the amount bet to the “bank”.
If the players guess matched the 3rd roll than add the amount bet to the bank.
-If the players guess did NOT match any roll then subtract the bet from the “bank”.
Let the player keep on playing until they enter a “0” (zero) as the bet OR when their bank reaches “0” (zero).
NO USE OF BREAK OR EXIT()

The 0 check should call exit
if get_bet == '0':
print('Thanks for playing!')
exit()
If you prefer not to use exit or break, you need to exit the main loop using a condition
Update total_bank
if get_bet == '0':
print('Thanks for playing!')
return bank, bet
Update the main loop
bet = 1 # to start loop
while rcnt < 4 and bet: # exit loop if bet=0
rcnt = 0
bank,bet = total_bank(bank)
if not bet: continue # exit game if bet = 0
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank
else:
if bet: # bet = 0 if game end
bank = bank - bet
if bank == 0:
print(f'You have ${bank} in your bank.')
print('Thanks for playing!')

you're returning to
while rcnt < 4:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank
after breaking from loop inside total_bank(bank):
you can modify the main loop to break if bet==0 by modifying it as follows
while rcnt < 4:
rcnt = 0
bank,bet = total_bank(bank)
if bet==0 :
break;
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank
EDIT - doing it without a break.
Check if bet!=0 before executing the loop.
Just initialise bet to any value other than zero.
bet=1
while (rcnt < 4) and (bet!=0):
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * 1.5
elif guess == rollDice(rcnt+3):
bank = bank

to get your first line of needed output change your print statement to
print('You have ${} in your bank.'.format(bank))

Related

how do i use loop with double input. first asks for a letter then the output then asks if u wanna play again or quit(1, 2)

so basically I want to start with the door input then check if the door has money or not then ask the user again if he would like to play again using the play input. if user enters 2 then asks again which door and so on. if the user enters 2 or if the number of miss on the door(no money) is = 3 then the game stops. right now the problem is it will run the loop jackpot ==1 till the it hits jackpot == 0 and play ==1 is not working
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
print()
play = input("Do you wish to quit (1) or open another door (2)?")
if play == "2" and miss <= 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
play == "1"
print("Congratulations!! You have won $", total, ".")
else:
miss == "3"
print("Sorry the game is over. You win $", total, ". Try again.")
else:
print("try again")
Try this code see if this works, there were lots of mistakes I added break statements and refined the logic
import random
total = 0
miss = 0
prizeMoney = 0
door = input("Enter a character from A to Z representing the door you wish to open:")
while miss < 3:
if len(door) > 0:
jackpot = random.randint(0, 1)
if jackpot == 1:
prizeMoney = random.randint(500, 1000)
total = total + prizeMoney
print("Behind Door", door, " is", prizeMoney, "$")
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
elif jackpot == 0 :
print("Sorry, there is no hidden money behind Door", door, ".This is a miss.")
miss = miss + 1
play = int(input("Do you wish to quit (1) or open another door (2)?"))
if play == 2 and miss < 3 :
door = input("Enter a character from A to Z representing the door you wish to open:")
else:
print('only 3 miss allowed or you pressed quit')
print("Congratulations!! You have won $", total, ".")
break
else:
print("try again")
break

Is it possible to end a while loop with a try/except statement?

So the goal here is to end my while loop, or my script really if a user's bank amount reaches 0 (zero) or if the user inputs a 0 (zero) for bet amount to terminate the script. THE PROBLEM is that I am NOT allowed to use a break statement, and though the program works perfectly with exit(), I cannot use that either because we haven't "gotten there yet" via the book (the instructor wants us to use what we are learning in the book and not what we already know).
I am just really stumped. Part of it is because I struggle a lot with the try/except statements so maybe I am just doing something wrong there, or maybe I need to try a different loop. Maybe you guys can help?
Gonna post my code below. As far as I am concerned, everything works perfectly fine, but I cannot use exit() or break so I need some advice on another python basics-orientated method...
So can I use try/except? If so, how?
I need the program to continue looping unless banking reaches 0 (zero) or user input is equal to 0 (zero), it's why I chose the while loop. Do I need to use a different loop method?
The help will be GREATLY appreciated and I thank everyone in advance.
import random
def rollDice(cnt):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
x = int(die1 + die2)
print('Roll #', cnt, 'was', x)
return x
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
exit()
bet = int(get_bet)
return bank,bet
def get_guess():
guess = 0
while (guess < 2 or guess > 12):
try:
guess = int(input('Choose a number between 2 and 12: '))
except ValueError:
guess = 0
return guess
bank = 500
guess = get_guess
rcnt = 1
while rcnt < 4:
rcnt = 0
bank,bet = total_bank(bank)
guess = get_guess()
if guess == rollDice(rcnt+1):
bank += bet * 2
elif guess == rollDice(rcnt+2):
bank += bet * .5
elif guess == rollDice(rcnt+3):
bank = bank
else:
bank = bank - bet
if bank == 0:
print(f'You have ${bank} in your bank.')
print('Thanks for playing!')
exit()
You can certainly exit the loop using an exception; just raise an exception inside your while loop, and catch it outside the loop:
def total_bank(bank):
bet = 0
try:
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
if get_bet == '0':
print('Thanks for playing!')
raise StopIteration()
bet = int(get_bet)
except StopIteration:
pass
return bank,bet
But even easier is just to return from inside the loop:
def total_bank(bank):
bet = 0
while bet <= 0 or bet > min([500,bank]):
print(f'You have ${bank} in your bank.')
get_bet = input('Enter your bet (or 0 to quit): ')
bet = int(get_bet)
if get_bet == '0':
print('Thanks for playing!')
return bank, bet
return bank, bet
I'm not super knowledgable with the try and except functions but with the try block you could raise an error and end the program like that.

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

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.

Python - Does input keep a value if not stored in a variable?

So I am doing a roulette like loop, which works well, except it sometimes stop at the "# end condition" part (10 lines up from bottom), often after 2 loops. Is there something to know about input() keeping its value or something like that even without a var or am I doing something wrong ?
# -*-coding:utf-8 -*
import os, math, random
user_number = 50
cash = 0
balance = 0
go_on = True
while go_on:
# to_find init
to_find = random.randrange(50)
# bet and cash init
if cash == 0:
temp = input("How many cash do you bet ?\n")
if int(temp) > 0:
cash = int(temp)
else:
continue
temp = input("Which number do you bet on (0 to 49) ?\n")
if int(temp) >= 0 and int(temp) <= 49:
user_number = int(temp)
else:
continue
# cash modif
if user_number == to_find:
balance += cash * 3
cash *= 4
print("Woot we got a winner\nYou're now at,", cash, "$ !\nThe number was", to_find, "\n")
elif user_number % 2 == to_find % 2:
balance += math.ceil(cash / 2)
cash = cash + math.ceil(cash / 2)
print("Yay you got some money\nYou're now at", cash, "$ !\nThe number was", to_find, "\n")
else:
balance -= cash
cash = 0
print("Sometime you win... And sometime, you're back to 0 !\nThe number was", to_find, "\n")
# end condition
print("Your current balance is at", balance, "\n")
if input("Want to try again ? Hit enter ! \nElse enter a number\n") == "":
pass
else:
go_on = False
print("See you soon !")
if balance < 0:
print(" And better luck next time !")
os.system("pause")
You have an infinite loop: If you hit the bottom of the loop while cash is not 0, then on the next iteration, you'll hit the else part of your cash == 0 condition whose continue takes you back to the beginning of the loop, which will then repeat forever.
Looking at what you are trying to do, my best guess would be that you have assumed that continue works like pass (which does nothing, and is equivalent to omitting the else-part entirely).
In order to figure out what is going on is situations like these, it might be a good investment to get familiar with a debugger, which would allow you to stop the code at any line and investigate the values of each of your local variables. There are plenty of those around, but an example of a good free one is PyCharm Community.

Categories