python blackjack ace problem which breaks my code - python

I currently am making a blackjack python minigame, where a player plays until he gets a blackjack or stands and returns the value of his deck. This game does not play against a dealer and instead just uses his hands as a score. My problem is, I cannot figure out a way to make aces go from 11 to 1 without looping and breaking the program. Here is my code:
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
while len(player) != 2:
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1:
total -= 10
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()

if "A" in player will always be True once there's an ace in the deck, and so you never get to the else where you print "BUST!" and return, so the loop just continues. You can do something like incremeting count for every ace in the deck and then change the ace part to be:
if total > 21:
player_aces = player.count("A") # How many aces the player has
if player_aces != count: # Meaning there are aces that weren't checked
for _ in range(player_aces - count):
total -= 10 # Could also be simplified to: total -= 10 * (player_aces - count)
count = player_aces
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
Also, if action_taken != "hit" or "stand" doesn't check that action_taken is not "hit" and not "stand". An or treats both its inputs as bool values and returns whether at least one is True. The != operator has precedence over or, so the line is actually if (action_taken != "hit") or "stand". The left part of that does what it's supposed to do, but then the right part evaluates "stand" as a bool, and in python every non-empty string is evaluated as True. So the right expression is always True, and so is the or - and the program will always enter the if statement.
You probably want: if action_taken != "hit" and action_taken != "stand".

There were a coupe of issues that I have fixed. I have created a counter for the number of Aces, this allows us to count how many times we can reduced the total by - otherwise we just keep removing 10.
Also the indentation of the last else statement needed moving out.
import random
def play():
output = "Your hand: "
player = []
total=0
count = 0
reducedA = 0
while len(player) != 2:
card = 1
#card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
reducedA+=1
player.append("A")
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) == 2:
print(f"{output} ({total}) ")
while len(player) >= 2:
action_taken = input("Would you like to 'hit' or 'stand': ")
if action_taken == "hit":
card = random.randint(1,52)
if card <= 4:
output += "A "
total += 11
player.append("A")
reducedA += 1
elif card <= 8:
output+="2 "
total+=2
player.append("2")
elif card <= 12:
output+="3 "
total+=3
player.append("3")
elif card <= 16:
output+="4 "
total+=4
player.append("4")
elif card <= 20:
output+="5 "
total+=5
player.append("5")
elif card <= 24:
output+="6 "
total+=6
player.append("6")
elif card <= 28:
output+="7 "
total+=7
player.append("7")
elif card <= 32:
output+="8 "
total+=8
player.append("8")
elif card <= 36:
output+="9 "
total+=9
player.append("9")
elif card <= 40:
output+="10 "
total+=10
player.append("10")
elif card <= 44:
output+="J "
total+=10
player.append("J")
elif card <= 48:
output+="Q "
total+=10
player.append("Q")
elif card <= 52:
output+= "K "
total+=10
player.append("K")
if len(player) >= 2 and total <=21:
print(f"{output} ({total}) ")
if total > 21:
if "A" in player: #Ask why ace always messes up
if count < 1:
count +=1
total-=10
print(f"{output} ({total}) ")
if player.count("A") > 1 and reducedA:
total -= 10
reducedA -= 1
print(f"{output} ({total}) ")
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
else:
print(f"{output} ({total}) ")
print("BUST!")
return total
if action_taken == "stand":
return total
if action_taken != "hit" or action_taken != "stand":
print("Enter a valid input ('hit' or 'stand') ")
play()

Related

Blackjack python game

I have to create a blackjack game in python in which the user inputs the number of decks that are being used and the amount of money the user wants to bet. The rules are: o The player places his bet (should be read from the keyboard).
o The dealer and player are dealt two cards (one card of the dealer should be hidden).
o If the player has 21 he wins his bet; else if the dealer has 21 then the dealer wins and the player loses his bet.
o The player can only select to draw a new card (hit) or pass. Repeat until the player passes or busts. If the player goes above 21 then he busts.
o Then the dealer draws cards (automatically) until he either busts or reaches 17 or higher.
o Values of cards: A= 1 or 11 (the highest that does not bust you) and J=Q=K=10
o Note: in blackjack there are more actions: insurance, double, split; those are not required to be implemented as they would make the code you have to produce much, much longer and harder
I will show you my code below when I tried to run it, it said that the name "total" is not defined on the function game, but earlier on I have already defined it. I don't know how can i fix it.
import random
N=int(input("Please enter number of decks of cards used: "))
deck= [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
wins=0
losses=0
chip_pool = 100
bet = 1
def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card=deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def play_again():
again = input("Do you want to play again? (Y/N) : ").lower()
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*N
game()
else:
print("Thank you for playing.")
exit()
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
def hit(hand):
card = deck.pop()
if card == 11:
card = "J"
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def print_results(dealer_hand, player_hand):
clear()
print("\n WELCOME TO BLACKJACK!\n")
print("The dealer has a " + str(dealer_hand) + "for a total of" + str(total(dealer_hand)))
print("You have a" + str(player_hand) + "for a total of" + str(total(player_hand)))
def blackjack(dealer_hand, player_hand):
global wins
global losses
if total(player_hand) == 21:
print_results(player_hand,dealer_hand)
print("Congratulations! You got a blackjack.\n")
wins = wins + 1
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand,player_hand)
print("Sorry you lose. The dealer got a blackjack.\n")
chip_pool -= bet
loses = loses + 1
play_again()
def score(dealer_hand,player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print("Congratulations! You got a blackjack1\n")
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print("Sorry you lose. The dealer go a blackjack\n")
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print("Sorry, you busted. You lose.\n")
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print("Dealer busts. You win!\n")
chip_pool += bet
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Sorry, the score is not higher than the dealer. You lose.\n")
chip_pool -= bet
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print("Congratulations. Your score is higher than the dealer. You win.\n")
chip_pool += bet
elif total(player_hand) == total(dealer_hand):
print_results(playe_hand, dealer_hand)
print("There is a tie. In a tie dealer always wins!\n")
chip_pool -= bet
def make_bet():
global bet
bet = 0
print("What amount of chips would you like to bet? ")
while bet == 0:
bet_comp = input()
bet_comp = int(bet_comp)
if bet_comp >= 1 and bet_comp <= chip_pool:
bet = bet_comp
else:
print("Invalid bet, you only have" + str(chip_pool) + "remaining")
def game():
choice = 0
print("Welcome to Blackjack!\n")
dealer_hand = deal(deck)
player_hand = deal(deck)
print("The dealer is showing a " +str(dealer_hand[0]))
make_bet()
print("You have a " + str(player_hand))
blackjack(dealer_hand, player_hand)
quit = False
while not quit:
choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
if choice == 'h':
hit(player_hand)
print(player_hand)
if total(player_hand) > 21:
print("You busted")
chip_pool -= bet
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
print(dealer_hand)
if total(dealer_hand) > 21:
print("Dealer busts. You win!")
chip_pool += bet
play_again()
score(dealer_hand, playe_hand)
play_again()
elif choice == "q" :
print("Thank you for playing. Hope you enjoyed!")
quit = True
exit()
if __name__ == "__main__":
game()
You have not defined the function total that you call. Try adding this to your code
def total(array):
total = 0
for card in array:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
However I see some more issues in your code that will need fixing later on! Stand or Quit do nothing currently, and on busting there is an exception thrown since chip_pool never had a value assigned to it
EDIT 1:
You defined a function
def total_hand():
total = 0
for card in hand:
if card == "J" or card == "Q" or card == "K":
total = total + 10
elif card == "A":
if total >=11:
total = total + 1
else:
total = total + 11
else:
total = total + card
return total
Similar to what I suggested. Maybe it was just a typo but you need to do the following
Rename the function from total_hand to total OR call total_hand
Change the definition from total_hand() to total_hand(hand)

Why is python not taking my input and using it?

It just skips over the fact that I put no when it asks I put no, and when I do put no, it just re-asks me if I want to hit.
I've tried making a new while statement for when you don't want to hit and it still didn't work.
import time
from random import randint
cardg = 0
cardg1 = 0
yeet = 1
while cardg < 21:
hit = input("Do you want to hit? (Yes or No): ")
if hit == "yes" or hit == "Yes":
num = randint(1, 10)
num2 = randint(1, 4)
card = num
card2 = num2
if num == 1:
card1 = "Ace"
elif num == 11:
card1 = "Jack"
elif num == 12:
card1 = "Queen"
elif num == 13:
card1 = "King"
if num2 == 1:
card2 = "Hearts"
if num2 == 2:
card2 = "Diamonds"
if num2 == 3:
card2 = "Spades"
if num2 == 4:
card2 = "Clubs"
if num == 1:
card = input("Would you like your ace to be a 1 or 11?\nAnswer: ")
print("Ace of " + str(card2))
cardg += int(card)
time.sleep(1)
if cardg < 21:
print(str(card) + " of " + str(card2))
elif cardg == 21:
time.sleep(1)
print(str(card) + " of " + str(card2))
print("Blackjack, you win!")
yeet = 0
elif cardg > 21:
print(str(card) + " of " + str(card2))
print("Busted, you lose.")
yeet = 0
else:
while cardg1 < 21 and cardg1 > 18:
num = randint(1, 11)
cardg1 += int(num)
num2 = randint(1, 4)
card = num
card2 = num2
if num == 1:
card1 = "Ace"
elif num == 11:
card1 = "Jack"
elif num == 12:
card1 = "Queen"
elif num == 13:
card1 = "King"
if num2 == 1:
card2 = "Hearts"
if num2 == 2:
card2 = "Diamonds"
if num2 == 3:
card2 = "Spades"
if num2 == 4:
card2 = "Clubs"
cardg1 += int(card)
time.sleep(1)
if cardg1 < 21 and cardg1 > 18:
print(str(card) + " of " + str(card2))
print("You have " + str(cardg) + " points, dealer has " + str(cardg1) + " points.")
if cardg > cardg1:
print("Dealer has won!")
yeet = 0
else:
print("You have won!")
yeet = 0
elif cardg1 == 21:
time.sleep(1)
print(str(card) + " of " + str(card2))
print("Dealer has blackjack, you lose!")
yeet = 0
elif cardg1 > 21:
print(str(card) + " of " + str(card2))
print("Dealer busted, you win!")
yeet = 0
When ran, this is this output. The getting 21 and busting code works.
Do you want to hit? (Yes or No): yes
3 of Clubs
Do you want to hit? (Yes or No): yes
9 of Hearts
Do you want to hit? (Yes or No): no
Do you want to hit? (Yes or No): n
Do you want to hit? (Yes or No): no
Do you want to hit? (Yes or No):
cardg1 is initialized to 0. Therefore, the while condition cardg1 < 21 and cardg1 > 18 fails, as 0 is not in between 18 and 21, hence the else block does nothing.

Python repeat random integer in while loop

I am trying to code player and mob attacks for a text based RPG game I am making, I have randomint set up for player and mob hitchance and crit chance but I can't figure out how to get a new integer for them every time I restart the loop, it uses the same integer it got the first time it entered the loop.
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
roll = roll_dice()
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
while True:
roll.mobcrit
roll.mobhitchance
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
if roll.mobcrit <= 5 and roll.mobhitchance >= 25:
print("\nOrc crit for",str(orcMob.atk * 2),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk * 2
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance >= 25:
print("\nOrc hit for",str(orcMob.atk),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk
print("Your HP",str(userPlayer.hp))
break
elif roll.mobcrit <= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
elif orcMob.hp >= 1:
continue
The problem is with your roll_dice class. You have the values defined when the class initializes, but then you never update them again. Therefore self.escape or self.spawn will always be the same value after the program starts. The easiest way to solve your problem without rewriting much would be to make another instance of roll_dice() every time you want to roll the dice. Something like:
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
# roll = roll_dice() # you don't need to make an instance here
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll = roll_dice() # make a new instance with each loop
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
Use functions like
import random
for x in range(10):
print random.randint(1,101)
use a array around for a max 100 people and generate random digits to add in your code.
You can also use a array to create random umber structure and then use the numbers to be shuffled and added as you create them
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

Storing a Function

import sys
print("Hello I am FoodBot, welcome to Fire n' Fusion. Please choose your item in each category.")
print("When I ask for your choices enter the code of the menu item.")
menuname= str(input("What is the name you would like your order placed under:"))
questioninput= int(input("Would like to eat here or would you like your order to-go? Enter 1 for eating here and 2 if you would like your meal to-go:"))
if questioninput < 1 or questioninput > 2:
sys.exit("Sorry there was an error in your input. Please retry!")
print("Here are the appetizers...")
print("-------------------------------")
print("Honey Chilli Potatoes($3.20) - Use Code 1")
print("Paneer Lettuce Wraps($5.10) - Use Code 2")
print("Mini Chicken Tamales($3.55) - Use Code 3 ")
print("Fiery Chicken Meatballs($5.99) - Use Code 4")
print("Enter 5 for Nothing")
appetizerinput = int(input("Enter what you would like in APPETIZERS[Code = 1-5]: "))
if appetizerinput == 1:
item_price_app = 3.20
elif appetizerinput == 2:
item_price_app = 5.10
elif appetizerinput == 3:
item_price_app = 3.55
elif appetizerinput == 4:
item_price_app = 5.99
elif appetizerinput == 5:
item_price_app = 0.00
elif appetizerinput < 1 or appetizerinput > 5:
sys.exit("Sorry there was an error in your input. Please retry!")
print("Here are the Entrees...")
print("-------------------------------")
print("Gobi Munchurian($7.21) - Use Code 6")
print("Grilled Veggie Skewers($5.33) - Use Code 7")
print("Paneer Kathi Rolls($7.79) - Use Code 8")
print("Lemon and Ginger Chicken($8.60) - Use Code 9")
print("Hot Chicken Lasagna($6.45) - Use Code 10")
print("Prisha's Favorite Chicken n'Cheese Enchiladas ($7.84) - Use Code 11")
print("Enter 12 for Nothing")
entreeinput = int(input("Enter what you would like in ENTREES [Code 6-12]:"))
if entreeinput == 6:
item_price_ent = 7.21
elif entreeinput == 7:
item_price_ent = 5.33
elif entreeinput == 8:
item_price_ent = 7.79
elif entreeinput == 9:
item_price_ent = 8.60
elif entreeinput == 10:
item_price_ent = 6.45
elif entreeinput == 11:
item_price_ent = 7.84
elif entreeinput == 12:
item_price_ent = 0.00
elif entreeinput < 6 or entreeinput > 12:
sys.exit("Sorry there was an error in your input. Please retry!")
print("Here are the Choices for Bread and Rice...")
print("-------------------------------")
print("Cumin Rice($2.25) - Use Code 13")
print("Egg Friedrice($3.25) - Use Code 14")
print("Plain Kulcha($1.50) - Use Code 15")
print("AlooKulcha($2.25) - Use Code 16")
print("Enter 17 for Nothing")
breadandriceinput = int(input("Enter what you would like in BREAD AND RICE [Code 13-17]:"))
if breadandriceinput == 13:
item_price_brice = 2.25
elif breadandriceinput == 14:
item_price_brice = 3.25
elif breadandriceinput == 15:
item_price_brice = 1.50
elif breadandriceinput == 16:
item_price_brice = 2.25
elif breadandriceinput == 17:
item_price_brice = 0.00
elif breadandriceinput < 13 or breadandriceinput > 17:
sys.exit("Sorry there was an error in your input. Please retry!")
print("Here are the Choices for Desserts...")
print("-------------------------------")
print("Arabic King-Sweets($3.99) - Use Code 18")
print("Coconut Fried IceCream($2.50) - Use Code 19")
print("Supreme Vanilla Fudge($3.75) - Use Code 20")
print("Enter 21 for Nothing")
dessertinput = int(input("Enter what you would like in DESSERTS [Code 18-21]:"))
if dessertinput == 18:
item_price_des = 3.99
elif dessertinput == 19:
item_price_des = 2.50
elif dessertinput == 20:
item_price_des = 3.75
elif dessertinput == 21:
item_price_des = 0.00
elif dessertinput < 18 or dessertinput > 21:
sys.exit("Sorry there was an error in your input. Please retry!")
print("Here are the Choices for Drinks...")
print("-------------------------------")
print("Chai($1.00) - Use Code 22")
print("Cookies n' Cream Milkshake($2.50) - Use Code 23")
print("Bottle of Water($1.25) - Use Code 24")
print("FountainDrink($1.50) - Use Code 25")
print("Enter 26 for Nothing")
drinkinput = int(input("Enter what you would like in DRINKS [Code 22-26]:"))
if drinkinput == 22:
item_price_dri = 1.00
elif drinkinput == 23:
item_price_dri = 2.50
elif drinkinput == 24:
item_price_dri = 1.25
elif drinkinput == 25:
item_price_dri = 1.50
elif drinkinput == 26:
item_price_dri = 0.00
elif drinkinput < 22 or drinkinput > 26:
sys.exit("Sorry there was an error in your input. Please retry!")
sauceinput = str(input("Would you like a sauce platter with your meal(enter Yes or No)FREE!:"))
def mybill():
print(" ")
print(" ")
print(" ")
print(" ")
print(" -----Fire n' Fusion------")
if questioninput == 1:
print("Meal:EATING IN THE RESTARAUNT")
elif questioninput == 2:
print("Meal:TO-GO ORDER")
if appetizerinput == 1:
print("Honey Chilli Potatoes: " + " $3.20")
elif appetizerinput == 2:
print("Paneer Lettuce Wraps: " + " $5.10")
elif appetizerinput == 3:
print("Mini Chicken Tamales: " + " $3.55")
elif appetizerinput == 4:
print("Fiery Chicken Meatballs: " + " $5.99")
if entreeinput == 6:
print("Gobi Munchurian: " + " $7.21")
elif entreeinput == 7:
print("Grilled Veggie Skewers: " + " $5.33")
elif entreeinput == 8:
print("Paneer Kathi Rolls: " + " $7.79")
elif entreeinput == 9:
print("Lemon and Ginger Chicken: " + " $8.60")
elif entreeinput == 10:
print("Hot Chicken Lasagna: " + " $6.45")
elif entreeinput == 11:
print("Prisha's Favorite Chicken n' Cheese Enchiladas:" + "$7.84")
if breadandriceinput == 13:
print("Cumin Rice: " + " $2.25")
elif breadandriceinput == 14:
print("Egg Fried Rice: " + " $3.25")
elif breadandriceinput == 15:
print("Plain Kulcha: " + " $1.50")
elif breadandriceinput == 16:
print("Aloo Kulcha: " + " $2.25")
if dessertinput == 18:
print("King-Sweets: " + " $3.75")
elif dessertinput == 19:
print("Coconut Fried Ice Cream: " + " $2.50")
elif dessertinput == 20:
print("Supreme Vanilla Fudge: " + " $3.75")
if drinkinput == 22:
print("Chai: " + " $1.00")
elif drinkinput == 23:
print("Cookies n' Cream Milkshake:" + "$2.50")
elif drinkinput == 24:
print("Bottle of Water: " + " $1.25")
elif drinkinput == 25:
print("Fountain Drink: " + " $2.50")
totalcost = round(item_price_app + item_price_ent + item_price_brice + item_price_des + item_price_dri, 2)
print("Order Name:" + menuname)
print(" Total:" + str (totalcost))
taxresult = round(totalcost*0.0775, 2)
print(" Tax:" + str (taxresult))
mysubtotal = round(totalcost+taxresult, 2)
print(" Subtotal:" + str (mysubtotal))
print("-------HEAD TO THE CASHIER TO PAY-------")
print(" --Thank you For Choosing Fire n' Fusion--")
print(" *********ENJOY YOUR MEAL!*********" )
mybill()
This above is my code. You will notice that I have a function called mybill in it. I need someone to explain to me how to store the output of the bill in a file so the restaurant manager can go back, use user input to enter a date, and see all the bills that were from that specific date he entered. I do not need my whole code to be stored, I only need the output of each of the times a bill is printed to be stored by the date it was printed. Thanks.
You could use python's datetime package for the current date and time
import datetime
now = datetime.datetime.now()
See here for additional information
And then use python's built in file management stuff to read/write to/from a csv file
receipt_file= open("Receipts.csv", 'a')
receipt_file.write(str(now.year) +',' + str(now.month) + ',' str(now.day) + ',' + str(total_cost))
receipt_file.close()
And when you read it back in to sort by user input, you could even split by year, month, and day
receipt_file= open("Receipts.csv", 'r')
for line in receipt_file.readlines():
year = line.split(',')[0]
month = line.split(',')[1]
# And so on - maybe even add list of receipts found with given criteria?
There are probably many options to do this, depending on how fancy you want to be and how adept you are at programming. A database would probably be ideal, but you could use a simple dictionary.
Using a dictionary with date keys:
sales = {date1: {sale1:[], sale2:[]..., date2: {sale1:[], sale2:[]...}
If you have a dictionary stored as a pickle, you could work this into your code (modifying as needed).
import pickle
import datetime as dt
# define today's date
heute = dt.date.today()
with open('data.p', 'rb') as fid:
data = pickle.load(fid)
# when adding data to your dictionary
if heute not in data:
data[heute] = {}
# add sale
item = 'soup'
cost = 5.60
quantity = 4
salenum = 'sale' + str(len(data[heute]) + 1)
data[heute][salenum] = {}
data[heute][salenum][item] = {}
data[heute][salenum][item]['cost'] = cost
data[heute][salenum][item]['quantity'] = quantity
# store data to pickle
with open('data.p', 'wb') as fid:
pickle.dump(data, fid)
When you want to get sales for each day:
with open('data.p', 'rb') as fid:
data = pickle.load(fid)
# specify date of interest
doi = dt.date(2017, 1, 1)
if doi not in data:
print('No sales today!')
else:
for sale in sorted(data[doi]):
for item in data[doi][sale]:
print(item + 'x' + data[doi][sale][item]['quantity'] + ' # $' + data[doi][sale]['cost'] + ' each')
This is just a general outline of something you could do with a dictionary, and should be easily modifiable for your needs.
NOTE
This code is not ready to run (don't copy/paste), it is just an example of one option that will work (tweaking required).
You can open a simple text file with append functionality and write all the strings one by one in bill and store that bill with some naming convention so that you can open that bill again with your code in future by passing that name string (i.e the bill date).
To write your output in code to bill text file you can do the following:
You have multiple print statements in a method. You can assign those to a string and print them in terminal as well copy them to your text file.
def mybill():
with open("bill.txt", "a") as mybillfile:
# use following structure for every print statement
str = " -----Fire n' Fusion------"
myfile.write(str)
print(str)

TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

I am currently five weeks into learning Python, and I am trying to program a very simplified version of Blackjack. I am close to done, but I cannot get past this certain error message:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
Here is the code:
import random
print("Welcome to my Black Jack program! Let's play!\n")
def deal_card():
Jack = 10
Queen = 10
King = 10
Ace = 1
cards = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King]
drawn_card = cards[random.randrange(1, 13)]
return drawn_card
def get_player_score():
first_player_card = deal_card()
second_player_card = deal_card()
sum_player_cards = first_player_card + second_player_card
print ("Your card total is: ", sum_player_cards, ".", sep="")
while sum_player_cards < 21:
choice = int(input("Would you like to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. "))
if choice == 1:
new_card = deal_card()
sum_player_cards = sum_player_cards + new_card
print ("Your new total is: ", sum_player_cards, ".", sep="")
elif choice == 2:
return()
else:
print("Please choose 'hit' or stay'.")
choice = input("Would you like to hit or stay? Enter 1 for 'hit' or 2 for 'stay'. ")
if sum_player_cards > 21:
return()
return int(sum_player_cards)
def get_dealer_score():
first_dealer_card = deal_card()
second_dealer_card = deal_card()
sum_dealer_cards = int(first_dealer_card + second_dealer_card)
while sum_dealer_cards <= 16:
another_dealer_card = deal_card()
sum_dealer_cards = sum_dealer_cards + another_dealer_card
if sum_dealer_cards > 16:
print("The dealer's card total is: ", sum_dealer_cards, ".", sep="")
return int(sum_dealer_cards)
def main():
player_score = get_player_score()
dealer_score = get_dealer_score()
if player_score > dealer_score and player_score <= 21:
print("You win!")
elif dealer_score > player_score and dealer_score <= 21:
print("The dealer wins!")
elif dealer_score <= 21 and player_score > 21:
print("You've gone bust! Dealer wins!")
elif dealer_score > 21:
print("The dealer busts! You win!")
main()
I am barely five chapters into Starting Out with Python, 4th ed. So I should only be using principles covered through those first five chapters.
Okay, thanks to #Evert and #Wiggy A., I fixed the return statements in my get_player_score function. Instead of return 0 or return, I realized I needed to change the statements to return sum_player_cards. I thought that return statements could only return values when used at the end of a function definition. But they can be used in if, elif, and else statements as well. Thanks for the input.

Categories

Resources