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
Related
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.
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))
money = 0
day = 1
items = []
def gameplay():
global items
global money
global day
energy = 10
work = 0
while True:
print("Type 'help' for assistance")
play = str(input("-> ")).strip()
if play.lower() == "help":
print("""
Type : To : Cost:
'Work' Get Money (only once then next day) 5 Energy
'Mall' Buy Stuff 5 Energy
'Items' Check Inventory N/A
'Money' Check Balance Of Money N/A
'Energy' Check Balance Of Energy N/A
'Day' Check your day, day 1 , day 2 etc. N/A
'Done' End Your Day N/A """)
elif play.lower() == "work":
if work == 1:
print("You have already worked!")
else:
energy -= 5
print("Working......")
money += 5
work += 1
print("You now have $%s and %s Energy" % (money, energy))
elif play.lower() == "mall":
energy -= 5
while True:
print("What do you want to do?")
print("""
Type : To: Cost:
Coffee Buy Normal Coffee : +2 energy next day $4
Lottery Buy A Lottery Ticket (per day) $10
Money Check Balance Of Money N/A
Energy Check Balance Of Energy N/A
Items Check Your Inventory N/A
Exit Exit the shopping mall N/A
""")
mall = input("-> ").strip()
if mall.lower() == "coffee":
if "coffee" in list:
print("You have already bought a cup of coffee!")
elif money < 4:
print("You don't have enough money!")
else:
print("You bought a coffee")
items.append("coffee")
print(items)
if mall.lower() == "lottery":
if "Lottery Ticket" in list:
print("You have already bought a ticket! Try again next day!")
lot = random.randint(1, 20)
jack = random.randint(100, 1000)
while True:
if money < 10:
print("You don't have enough money!")
break
else:
list.append("Lottery Ticket")
money -= 10
print("Choose a number between 1 to 20")
try:
lotg = int(input("-> "))
if lotg == lot:
print("Congratulations you have won $%s" % (jack))
money += jack
break
elif lotg != lot:
print("Sorry but you lost! Good luck Next Time")
break
except ValueError:
print("Please Type A Number")
elif mall.lower() == "money":
print("You currently have $%s" % (money))
elif mall.lower() == "energy":
print("You currently have %s" % (energy))
elif mall.lower() == "items":
print("These are your following items:")
print(items)
elif mall.lower() == "exit":
print("Exiting mall......")
break
elif play.lower() == "items":
print("These are your following items:")
print(items)
elif play.lower() == "money":
print("You currently have $%s" % (money))
elif play.lower() == "energy":
print("You currently have %s" % (energy))
elif play.lower() == "day" :
print("Its Day %s " % (day))
elif play.lower() == "done":
while True:
print("Are You Sure?")
sure = str(input("-> "))
if sure.lower() not in ["yes","no"]:
print("Please Type Yes Or No ")
elif sure.lower() == "yes":
print("Going Home For Next Day........")
home()
elif sure.lower() == "no":
print("Okay!")
break
def noenergy():
print("You don't have enough energy to do that")
def home():
print("You are at home..")
gameplay()
It sometimes shows:
Traceback (most recent call last):
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 120, in <module>
gameplay()
File "/home/alex/.config/JetBrains/PyCharm2020.1/scratches/scratch_718.py", line 50, in gameplay
if "coffee" in list:
TypeError: argument of type 'type' is not iterable
when i test it in this order
input -> mall
input -> coffee
The error message should pop up
Tried to change the while loop part to a for loop but , still the same and I can't find any answers on a single website
Why is this happening? The loop? The list? The input?
list is not a variable containing a list, it's the type (hence the error message) of list objects.
It looks like you meant to use the variable items which is a list and forgot or got confused.
Im having a logic confusion here and don't know whether a solution is possible with my setup.
I am trying to prompt the user for (in order)
user answer y/n (originally set to 'y')
a bet (based on their current money)
a guess on a number 1-6.
Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.
My code below works, if the user answers with a valid guess all the time:
def roll():
return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]
# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0
# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
break
But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?
I've tried
if (int(guess) < 1 or int(guess) > 6):
guess = input('What number are you betting on? (number 1-6)')
at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.
Is my setup all wrong or how can I fix this?
Updated attempt:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
break
if(userAnswer.strip().lower() != 'y'):
break
From a quick glance your problem seems to lie in the fact that when you enter an invalid guessing number, you never enter the third and final loop.
guess = input('What number are you betting on? (number 1-6)')
while (int(guess) >= 1 and int(guess) <= 6):
If you enter in a number that is < 1 or > 6 then you will never enter the while loop and directly jump to the break that is in the end of the second while loop which sends you back to the very first loop and asks you how much you want to bet again.
Try removing the break in the second while loop and see what happens, the logic is currently not what you are looking for.
Alright - this was the right way to do it:
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while userAnswer.strip().lower() == 'y':
while True:
bet = int(input('You have $' + str(money) + '. How much would you like to bet?'))
if bet <=0 or bet > money:
print('Invalid bet - bet must be greater than 0 and less than '+str(money))
continue
# Valid bet entered
break
while True:
guess = int(input('What number are you betting on? (number 1-6)'))
if guess < 1 or guess > 6:
print('Invalid guess - you must enter a value 1-6')
continue
# Valid guess entered
break
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
else:
print('You lost your bet :(')
money += int(computeBetResult(theRoll, bet, guess))
userAnswer = input('Would you like to play again (y/n)?')
Change the while condition in the loop that asks for a valued number and put it inside the actual loop, so that when it is an invalid number, it asks for another one.
Edited while condition because of #AMC 's comment
Edited to put the whole code that solves the problem:
def main():
money = 100
userAnswer = 'y'
print('Welcome to Gambling.')
while(userAnswer.strip().lower() == 'y'):
bet = input('You have $' + str(money) + '. How much would you like to bet?')
while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
guess = input('What number are you betting on? (number 1-6)')
while true:
if int(guess) < 1 or int(guess > 6):
guess = input("Please choose a valid number") #will keep asking for a valid number if it is wrong
continue
else:
print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
# Actually calculate the roll
theRoll = roll()
print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
if (int(computeBetResult(theRoll, bet, guess)) > 0):
print('You won your bet!')
money += int(bet)
else:
print('You lost your bet :(')
money -= int(bet)
print('You now have $' + str(money).strip())
# Prompt again
userAnswer = input('Would you like to play again (y/n)?')
if userAnswer=="n":
break
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.