why doesn't "break" stop a while loop (Python) [duplicate] - python

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed last year.
So I was doing a blackjack program. Everything was working until I got this:
Your cards: [2, 4]
Total: 6
Chose your next move: stand
Dealer's cards: [5]
Your cards: [2, 4, 10]
Total: 16
Chose your next move: stand
//////////////////////////
Dealer's cards: [5]
Your cards: [2, 4, 10, 10]
Total: 26
//////////////////////////
The loop is supposed to break when move == stand I think it's the break function, but there is a high chance I messed something else up.
Here's the bit of code I think is messing up:
while player_cards_total < 21:
player_cards_total = sum(player_cards)
dealer_cards_total = sum(dealer_cards)
if player_cards_total > 20:
print('\n\n//////////////////////////\nDealer\'s cards: ', dealer_cards)
print('Your cards: ', player_cards,'\nTotal: ', player_cards_total, '\n//////////////////////////')
print('\nBUST\n')
break
move = get_move()
if move == 'hit':
player_cards.append(get_card())
else:
break
The while loop is an individual loop, and not a inner loop
Here's the whole code
import time
Ace = 11
Jack = 10
Queen = 10
King = 10
cards = [Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King]
Ace_21 = False
player_bal = 0
dealer_bal = 0
player_cards = []
dealer_cards = []
player_cards_total = 0
dealer_cards_total = 0
card = ''
move = ''
moves = 0
def get_card():
return(int(cards[random.randrange(1, 13)]))
dealer_cards = [get_card(),]
player_cards = [get_card(), get_card()]
player_cards_total = sum(player_cards)
def get_move():
if moves == 0:
print('\nDealer\'s cards: ', dealer_cards)
print('Your cards: ', player_cards,'\nTotal: ', player_cards_total)
move = input('Chose your next move: ')
if move == 'h' or 'Hit':
move = 'hit'
elif move == 's' or 'Stand':
move = 'stand'
return(move)
while player_cards_total < 21:
player_cards_total = sum(player_cards)
dealer_cards_total = sum(dealer_cards)
if player_cards_total > 20:
print('\n\n//////////////////////////\nDealer\'s cards: ', dealer_cards)
print('Your cards: ', player_cards,'\nTotal: ', player_cards_total, '\n//////////////////////////')
print('\nBUST\n')
break
move = get_move()
if move == 'hit':
player_cards.append(get_card())
else:
break
if player_cards_total > 21:
print('You lose!!!')
elif player_cards_total == 21:
print('Great job, you win')
else:
print('DEALER\'S TURN')
while dealer_cards_total < 20:
dealer_cards_total = sum(dealer_cards)

get_move always returns 'hit', so the break can never run. This is caused by a logic error.
You need to change the following lines:
if move == 'h' or 'Hit':
#and
elif move == 's' or 'Stand':
Now to the right of "or" is a non-empty string so these if's will always be True.
Instead you need:
if move == 'h' or move == 'Hit':
#and
elif move == 's' or move == 'Stand':
This will actually test of move is equal to either string separately as you intended. Furthermore, you could also use this convention if you would like:
if move in ['h', 'Hit']:
#and
elif move in ['s', 'Stand']:

Related

How to make a while true statement in a program that already has a while true statement

I know the title is a little confusing but I want a way to ask the user if they want to play the game (blackjack) again. If they say 'y' the game restarts if they say 'n' it breaks. I tried adding a while true statement and it didn't work and I think its because I have a while true statement already in it.
Here's my code, if anyone has a way to ask if they want to play it would be very much appreciated
# Global Variables
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A' 'J', 'Q', 'K', 'A']
dealer_cards = []
player_cards = []
print('Dealing...')
# Create the dealcard function to deal a card when needed
def dealcard(turn):
card = random.choice(deck)
turn.append(card)
deck.remove(card) # Removes the card out of the deck so it cant repeat.
# Create the function to calculate the total cards that each player has
def totalvalue(turn):
totalvalue = 0
facecards = ['J', 'Q', 'K']
for card in turn:
if card in range(1, 11):
totalvalue += card # This adds the cards together
elif card in facecards: # Checks if a card is a face card (J, Q, K,)
totalvalue += 10 # This gives value to face cards
else: # This checks if they get an ace and what works the best in case when they get an ace
if totalvalue > 11: # If total is over 11 Ace counts as 1
totalvalue += 1
else: # If total is under 11 Ace counts as 11
totalvalue += 11
return totalvalue
for dealing in range(2):
dealcard(dealer_cards)
dealcard(player_cards)
print(f"The dealer's cards are {dealer_cards} and the total amount is {totalvalue(dealer_cards)}")
print(f"Your cards are {player_cards} and your total amount is {totalvalue(player_cards)}")
while True:
print(f"You now have a total of {totalvalue(player_cards)} with these cards {player_cards}")
playerchoice = (input('Would you like to do \n1.Hit \nor \n2.Stand\n'))
if playerchoice == '2':
break
dealcard(player_cards)
# If they chose to stand move on to dealers / computers turn
print("What will the dealer do?...")
# Create game logic
if totalvalue(dealer_cards) >= 18:
print(f"The dealer chose to stand their cards are {dealer_cards} with a total of {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) < 16:
dealcard(dealer_cards)
print(f"The dealer chose to hit their new cards are {dealer_cards} and their total is {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) == totalvalue(player_cards):
print(f"Its a tie you both have {totalvalue(player_cards)}")
if totalvalue(dealer_cards) == 21:
print(f"The dealer got blackjack! You lose...")
if totalvalue(player_cards) > 21:
print(f"You busted Dealer wins... Dealer had {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) > 21:
print(f"Dealer busted... You won and you had {totalvalue(player_cards)}")
if totalvalue(dealer_cards) > totalvalue(player_cards) < 21:
if totalvalue(dealer_cards) < 21:
print(f"Dealer wins they had a {totalvalue(dealer_cards)} and you had {totalvalue(player_cards)}")
if totalvalue(player_cards) > totalvalue(dealer_cards):
if totalvalue(player_cards) < 21:
print(f"You won, you had {totalvalue(player_cards)} and the dealer had {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) > 21:
if totalvalue(player_cards) > 21:
print(f"Both of you busted... no one wins its a tie")
# Print players and dealers card so user can see
print(f"Your cards were {player_cards} with a total of {totalvalue(player_cards)} \nthe dealers cards were {dealer_cards} and their total was {totalvalue(dealer_cards)}")
# Ask User if they want to play again
The while loop you created is only used for the card dealing part. But if you want to be able to loop the entire game again, you must create a second while loop which entirely contains the loop that you already created, and the entire "playing" part.
So you will need to shift everything by 1 indentation
Should look like this :
# define your functions and global variables
while True:
while True:
# Card dealing stuff
# Game logic and display results
# Wanna play again ?
I refactored your code. I added the block that asks if the player wants to play again. I also added a stats() function that keeps track of the score. The stats function is not 100% functioning because of the the way the if statements are written. Sometimes the score overlaps, but I'm sure you can figure it out! You get the gist, though.
At the bottom I included a tiny sample code of asking the user whether to perform an action over and over. It's a nice template for future code if you need.
**** UPDATE ****
New Improvements:
Added a 1-second delay with "Dealing..." message
Added error handling across the board. Now when user inputs any value except what's expected, code raises an exception and won't break. For example, when user is prompted to enter either 1 or 2, any other input will raise the exception.
Issues:
Still having problem with scoreboard because of how conditional statements are implemented, but I'll leave that to you, buddy... ;)
import random
import time
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10,
2, 3, 4, 5, 6, 7, 8, 9, 10,
2, 3, 4, 5, 6, 7, 8, 9, 10,
2, 3, 4, 5, 6, 7, 8, 9, 10,
'J', 'Q', 'K', 'A', 'J', 'Q',
'K', 'A', 'J', 'Q', 'K', 'A',
'J', 'Q', 'K', 'A']
dealer_cards = []
player_cards = []
player = 0
dealer = 0
def dealcard(turn):
card = random.choice(deck)
turn.append(card)
deck.remove(card)
def totalvalue(turn):
totalvalue = 0
facecards = ['J', 'Q', 'K']
for card in turn:
if card in range(1, 11):
totalvalue += card
elif card in facecards:
totalvalue += 10
else:
if totalvalue > 11:
totalvalue += 1
else:
totalvalue += 11
return totalvalue
#Added scorecard
def stats():
print('________________________')
print(f'Player\t\tDealer\n{player}\t\t{dealer}')
print('------------------------')
def msg():
print("Invalid entry. Try again.")
while True:
try:
options = int(input("[1] Play\n[2] Exit\nChoose action: "))
except ValueError:
msg()
else:
# if PLAY
if options == 1:
print('Dealing...')
time.sleep(1)
for dealing in range(2):
dealcard(dealer_cards)
dealcard(player_cards)
while True:
dealcard(player_cards)
print(f"You now have a total of {totalvalue(player_cards)} with these cards {player_cards}")
try:
playerchoice = int(input('\n[1] Hit\n[2] Stand\nWhat would you like to do? '))
except ValueError:
msg()
else:
if playerchoice == 1:
continue
else:
dealcard(dealer_cards)
if totalvalue(dealer_cards) >= 18:
print(f"The dealer chose to stand their cards are {dealer_cards} with a total of {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) < 16:
dealcard(dealer_cards)
print(f"The dealer chose to hit their new cards are {dealer_cards} and their total is {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) == totalvalue(player_cards):
print(f"Its a tie you both have {totalvalue(player_cards)}")
if totalvalue(dealer_cards) == 21:
print(f"The dealer got blackjack! You lose...")
dealer +=1
if totalvalue(player_cards) > 21:
print(f"You busted Dealer wins... Dealer had {totalvalue(dealer_cards)}")
dealer +=1
if totalvalue(dealer_cards) > 21:
print(f"Dealer busted... You won and you had {totalvalue(player_cards)}")
player +=1
if totalvalue(dealer_cards) > totalvalue(player_cards) < 21:
if totalvalue(dealer_cards) < 21:
print(f"Dealer wins they had a {totalvalue(dealer_cards)} and you had {totalvalue(player_cards)}")
dealer +=1
if totalvalue(player_cards) > totalvalue(dealer_cards):
if totalvalue(player_cards) < 21:
print(f"You won, you had {totalvalue(player_cards)} and the dealer had {totalvalue(dealer_cards)}")
player +=1
if totalvalue(dealer_cards) > 21:
if totalvalue(player_cards) > 21:
print(f"Both of you busted... no one wins its a tie")
stats()
break
#if EXIT
if options == 2:
print("Thanks for playing.")
break
# This block asks player whether to play again
# ***** BEGIN *****
again = input("Play again? Y/N: ").capitalize().strip()
if again == 'Y':
# This resets deck
dealer_cards = []
player_cards = []
elif again is not again.isalpha:
msg()
else:
print("Thanks for playing.")
break
# **** END ****
Sample code:
print("Add two numbers")
while True:
try:
num1 = int(input("Enter first num: "))
num2 = int(input("Enter second num:"))
res = num1 + num2
except ValueError:
print("Invalid entry. Try again.")
else:
print(f"{num1} + {num2} = {res}")
another = input("Add other two numbers? Y/N: ").capitalize().strip()
if another == 'Y':
another = True
continue
else:
print("Buh bye.")
break
We can accomplish this, as you expected, using a while loop. First, I’d suggest moving the function declarations and other constants, like the deck, to the top. Basically, anything that won’t change between rounds. Then, put a while True: right before the game starts, so before you deal the cards. Use middle click to select the first space in every line and indent. At the end of the round, take player input by using if input(‘Play again?: ‘).lower not in ‘y’, ‘yes’: break
I think the below code could help.
# Lumberjack
import random
# Global Variables
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10,
'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A' 'J', 'Q', 'K', 'A']
dealer_cards = []
player_cards = []
play_again = True
print('Dealing...')
# Create the dealcard function to deal a card when needed
def dealcard(turn):
card = random.choice(deck)
turn.append(card)
deck.remove(card) # Removes the card out of the deck so it cant repeat.
# Create the function to calculate the total cards that each player has
def totalvalue(turn):
totalvalue = 0
facecards = ['J', 'Q', 'K']
for card in turn:
if card in range(1, 11):
totalvalue += card # This adds the cards together
elif card in facecards: # Checks if a card is a face card (J, Q, K,)
totalvalue += 10 # This gives value to face cards
else: # This checks if they get an ace and what works the best in case when they get an ace
if totalvalue > 11: # If total is over 11 Ace counts as 1
totalvalue += 1
else: # If total is under 11 Ace counts as 11
totalvalue += 11
return totalvalue
for dealing in range(2):
dealcard(dealer_cards)
dealcard(player_cards)
while play_again:
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 3, 4, 5, 6, 7, 8, 9,
10,
'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A', 'J', 'Q', 'K', 'A' 'J', 'Q', 'K', 'A']
dealer_cards = []
player_cards = []
play_again = True
for dealing in range(2):
dealcard(dealer_cards)
dealcard(player_cards)
print(f"The dealer's cards are {dealer_cards} and the total amount is {totalvalue(dealer_cards)}")
print(f"Your cards are {player_cards} and your total amount is {totalvalue(player_cards)}")
while True:
print(f"You now have a total of {totalvalue(player_cards)} with these cards {player_cards}")
playerchoice = (input('Would you like to do \n1.Hit \nor \n2.Stand\n'))
if playerchoice == '2':
break
dealcard(player_cards)
# If they chose to stand move on to dealers / computers turn
print("What will the dealer do?...")
# Create game logic
if totalvalue(dealer_cards) >= 18:
print(f"The dealer chose to stand their cards are {dealer_cards} with a total of {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) < 16:
dealcard(dealer_cards)
print(f"The dealer chose to hit their new cards are {dealer_cards} and their total is {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) == totalvalue(player_cards):
print(f"Its a tie you both have {totalvalue(player_cards)}")
if totalvalue(dealer_cards) == 21:
print(f"The dealer got blackjack! You lose...")
if totalvalue(player_cards) == 21:
print(f"You got blackjack! You win...")
if totalvalue(player_cards) > 21:
print(f"You busted Dealer wins... Dealer had {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) > 21:
print(f"Dealer busted... You won and you had {totalvalue(player_cards)}")
if totalvalue(dealer_cards) > totalvalue(player_cards) < 21:
if totalvalue(dealer_cards) < 21:
print(f"Dealer wins they had a {totalvalue(dealer_cards)} and you had {totalvalue(player_cards)}")
if totalvalue(player_cards) > totalvalue(dealer_cards):
if totalvalue(player_cards) < 21:
print(f"You won, you had {totalvalue(player_cards)} and the dealer had {totalvalue(dealer_cards)}")
if totalvalue(dealer_cards) > 21:
if totalvalue(player_cards) > 21:
print(f"Both of you busted... no one wins its a tie")
# Print players and dealers card so user can see
print(
f"Your cards were {player_cards} with a total of {totalvalue(player_cards)} \nthe dealers cards were {dealer_cards} and their total was {totalvalue(dealer_cards)}")
# Ask User if they want to play again
if input('Do you want to play again? \n1.Yes \nor \n2.No\n') == "1":
play_again = True
else:
print("Thank you for playing Lumberjack with us")
play_again = False
Here I just modified some game logic too. Hope it is helpful.

problem in logic over python code creating blackjack project

this is my code below
it is work right but the problem is in my logic if i asked the user if he wants another card the game reload from the start you can try it there https://replit.com/#KamalSalm/blackjack-start-1#main.py if you want
the code works right but the problem is in asked the user for another card
import random
import art
from replit import clear
############### Blackjack Project #####################
#Difficulty Normal 😎: Use all Hints below to complete the project.
#Difficulty Hard 🤔: Use only Hints 1, 2, 3 to complete the project.
#Difficulty Extra Hard 😭: Only use Hints 1 & 2 to complete the project.
#Difficulty Expert 🤯: Only use Hint 1 to complete the project.
############### Our Blackjack House Rules #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in the list have equal probability of being drawn.
## Cards are not removed from the deck as they are drawn.
## The computer is the dealer.
##################### Hints #####################
#Hint 1: Go to this website and try out the Blackjack game:
# https://games.washingtonpost.com/games/blackjack/
#Then try out the completed Blackjack project here:
# http://blackjack-final.appbrewery.repl.run
#deck
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
#logo blackjack
def logo():
"""show logo"""
print(art.logo)
#user cards
def add_card():
return random.choice(cards)
#the final cards
the_cards ={}
game_on = True
while game_on:
user_response = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower()
if user_response == "y":
clear()
the_cards["user_cards"] = [add_card() , add_card()]
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"] = [add_card()]
total_com = sum(the_cards['com_cards'])
print(art.logo)
print(f" your cards: {the_cards['user_cards']}, current score is :{total_user} ")
print(f" computer is first card is {the_cards['com_cards']}")
#ask user if he want another card or pass
if total_user == 21:
print("game over you win it's blackjack")
game_on = False
elif total_user < 21 and total_com < 21:
ask_user = input("would you choose another card ").lower()
if ask_user == "y":
total_user += add_card()
if total_com > 13:
total_com += add_card()
if total_com == 21:
print("game over it's blackjack com win")
elif total_user > total_com:
print("you have won upper hand")
elif total_user < total_com:
print("you have lost not good hand")
elif ask_user =="n":
if total_user > total_com:
print("you have won your cards beat com")
elif total_user < total_com:
print("you have lose com has bigger hands")
else:
if total_user > 21:
print("game over you lose it is over 21")
elif total_com > 21:
print("you win computer cards over 21 ")
elif user_response == "n":
print("game over you can try again if you like")
game_on = False
else:
print("you type it wrong try again")
without to give the complete solution, i just sugget to refactor your code with 2 while loops, to separate the game play from the another card:
# the final cards
the_cards = {}
launch_game = 'y'
while launch_game == 'y':
user_response = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ").lower()
game_on = True
total_user = 0
total_com = 0
while user_response == 'y' and game_on:
if total_user == 0:
the_cards["user_cards"] = [add_card(), add_card()]
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"] = [add_card(), add_card()]
total_com = sum(the_cards['com_cards'])
else:
the_cards["user_cards"].append(add_card())
total_user = sum(the_cards['user_cards'])
the_cards["com_cards"].append(add_card())
total_com = sum(the_cards['com_cards'])
print(f" your cards: {the_cards['user_cards']}, current score is :{total_user} ")
print(f" computer's card: {the_cards['com_cards']}, current score is :{total_com} ")
game_on = False
if total_user == 21:
print("game over you win it's blackjack")
continue
if total_com == 21:
print("game over you lose it's blackjack for computer")
continue
if total_user > 21:
print("game over you lose it is over 21")
continue
if total_com > 21:
print("you win computer cards over 21 ")
continue
ask_user = input("would you choose another card ").lower()
if ask_user == "y":
game_on = True
continue
else: #and if total_user == total_com?
if total_user > total_com:
print("you have won your cards beat com")
elif total_user < total_com:
print("you have lose com has bigger hands")
it will easier for you to trap problem in your code!

Need assistance on blackjack python project implementing hit/stand feature

im just working on a blackjack project and im new to coding so its a little tough trying to add new functions such as the hit/stand function. I have tried making a hit/stand function but im not sure how to actually add a new card to the total of the players cards and the dealer also. im just staring by adding the players to try and get some result but a am just stuck at this rate and have no idea how i can properly implement this. I have a sep file that stores the list of the deck and shuffle but is imported
import playing_cards
import random
player_hand = []
dealers_hand = []
hands = [[]]
#STAGE 1 - testing purpose only
# Testing code for step 1
##card = playing_cards.deal_one_card()
##print(card)
#Stage 2 - testing purpose only (PLAYERS HAND)
# Deal first card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
# Deal second card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
#ADDING UP BOTH CARDS
# Display the player's hand to the screen using a simple print statement
#print("Player's hand is ", player_hand)
#Stage 4 and 5
suits = {'C': 'Club', 'H': 'Heart', 'D': 'Diamond', 'S': 'Spade'}
names = {'2': '2', '3': '3', '4': '4',
'5':'5', '6': '6', '7': '7', '8': '8', '9': '9', 'T': '10','J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}
def score_hand(player_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in player_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in player_hand)
score -= adjustment
return score
#ask about this
def show_result(player_hand):
player_score = int(score_hand(player_hand))
if player_score > 21:
print('*** Player Bust! ***')
elif player_score == 21:
print('*** Blackjack! Player Wins! ***')
##else:
## push(player_hand,dealer_hand)
##def push(player_score,dealers_score):
## print("Dealer and Player tie! It's a push.")
##else:
## // Logic to continue game
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
hit(show_hand,player_hand) # hit() function defined above
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
def show_hand(player_hand):
score_hand(player_hand)
score = f"Player's hand is {score_hand(player_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in player_hand])
return score + cards
for hand in hands:
print(show_hand(player_hand))
show_result(player_hand)
#Stage 3 - Testing purpose only (DEALERS HAND)
### Deal first card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Deal second card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Display the player's hand to the screen using a simple print statement
#Stage 4 and 5
def score_hand(dealers_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in dealers_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in dealers_hand)
score -= adjustment
return score
#ask about this
def show_result(dealers_hand):
dealers_score = int(score_hand(dealers_hand))
if dealers_score > 21:
print('*** Dealer Bust! ***')
elif dealers_score == 21:
print('*** Blackjack! Dealer Wins! ***')
def show_hand(dealers_hand):
score = f"Dealers's hand is {score_hand(dealers_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in dealers_hand])
return score + cards
for hand in hands:
print(show_hand(dealers_hand))
print('')
show_result(dealers_hand)
hit_stand(show_hand, player_hand)
import random
Dealer_Cards=[]
Player_Cards=[] # im also beginner in programming just little know some C from College
Total_Player=0 # and watched some tutorial like 5 min and get the whole algorithm
# then start thinking and coding i have little excuse like how to i
Total_Dealer=0 # stop when player or dealer hit >=21 expect option .
#Deal the cards
#Dealer Cards
while len(Dealer_Cards) != 2:
Dealer_Cards.append(random.randint(1,11))
if len(Dealer_Cards) == 2:
print("Dealer has ",Dealer_Cards)
# Player Cards
while len(Player_Cards) != 2:
Player_Cards.append(random.randint(1,11))
if len(Player_Cards) == 2:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Hit and if you want to Stay click '0']:")
option= int(input(""))
if option == 0:
Total_Dealer+= sum(Dealer_Cards) #Dealer_Cards= i
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards) # Player_Cards= x
print("sum of the Player cards:",Total_Player)
if Total_Dealer > Total_Player:
print("Dealer Wons")
break
elif Total_Player > Total_Dealer:
print("You Won")
break
else:
print("Scoreless.")
break
elif option == 1:
while len(Player_Cards) != 3:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 3:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option== 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 4:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 4:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option == 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 5:
Player_Cards.append(random.randint(1, 11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 5:
print("You have ",Player_Cards)
Total_Dealer+= sum(Dealer_Cards)
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards)
print("sum of the Player cards:",Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
Maybe this will get you on the right track (I couldn't find a 'hit' function defined, so you can do all the work right in hit_stand, as follows):
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
player_hand.append(playing_cards.deal_one_card())
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
That will solve how the player hits, but I didn't see logic in your code for the dealer to decide to hit or stand, which are based on standard house rules.

getting the correct value in blackjack [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a question about the sum of the cards dealt. When running the code, it doesn't give you the right amount of the two cards added up, i.e. cards [2, 8] would equal 24.. when it is only 10. What is going on? Any help is greatly appreciated!
Is there anything else that seems wrong? If any of my comments are wrong, please, feel free to correct me!
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4
def deal(deck): # deck function
hand = []
for i in range(2):
random.shuffle(deck) # shuffles deck
card = deck.pop() # removes and returns the value back to card
if card == 11: card = "J" # sets 11 to jack
if card == 12: card = "Q" # sets 12 to queen
if card == 13: card = "K" # sets 13 to king
if card == 14: card = "A" # sets 14 to ace
hand.append(card)
return hand
def play_again(): # ask payer if wants to play again function
again = raw_input("Do you want to play again? (Y/N) : ").lower()
if again == "y": # if answers yes, will give the player more cards
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] * 4 # sets deck to values of cards
game()
else:
print ("Bye!") # exits program
exit()
def total(hand):
total = 0 # start off with total of zero
for card in hand: # for the cards you dealt
if card == "J" or card == "Q" or card == "K": # if the card is j,q,k it equals 10
total += 10
elif card == "A":
if total >= 11: total += 1 # if the card is an A, if the total is more than 11, it makes the vaue 1
else:
total += 11 # makes the value of the ace 1 if the total is greater than 11
else:
total += card # adds up your cards
return total
def hit(hand):
card = deck.pop() # removes and returns the value back to card
if card == 11: card = "J" # setting the card number to the face value
if card == 12: card = "Q"
if card == 13: card = "K"
if card == 14: card = "A"
hand.append(card)
return hand
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
def print_results(dealer_hand, player_hand): # funtcion for results of hand
clear()
print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand))) # gives you dealers hand
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # gives you your hand
def blackjack(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand) # prints dealers and your hand
print ("Congratulations! You got a Blackjack!\n")
play_again()
elif total(dealer_hand) == 21: # if hand is more than 21,
print_results(dealer_hand, player_hand) # prints out dealer and your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
play_again()
def score(dealer_hand, player_hand):
if total(player_hand) == 21: # if your hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations! You got a Blackjack!\n")
elif total(dealer_hand) == 21: # if dealer hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
elif total(player_hand) > 21: # if your hand is greater than
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. You busted. You lose.\n")
elif total(dealer_hand) > 21: # if dealer hand is greater than 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Dealer busts. You win!\n")
elif total(player_hand) < total(dealer_hand): # if your hand is less than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. Your score isn't higher than the dealer. You lose.\n")
elif total(player_hand) > total(dealer_hand): # if your hand is higher than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations. Your score is higher than the dealer. You win\n")
def game():
choice = 0
clear()
print ("WELCOME TO BLACKJACK!\n") # welcomes player to game
dealer_hand = deal(deck) # deals to dealers
player_hand = deal(deck) # deals to player
while choice != "q":
print ("The dealer is showing a " + str(dealer_hand[0])) # shows what one of the dealers card is
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # shows you your hand
blackjack(dealer_hand, player_hand) # send inormation to blackjack funciton
choice = raw_input(
"Do you want to [H]it, [S]tand, or [Q]uit: ").lower() # gets user input on if they want to hit, stand, or quit
clear()
if choice == "h":
hit(player_hand) # adds a new card value to your exisiting han d
while total(dealer_hand) < 17: # dealer has to hit is value of cards below 17
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "q":
print("Bye!")
exit()
if __name__ == "__main__":
game()
The code you pasted has some indentation issues. I fixed that and ran the code, and getting proper results:
WELCOME TO BLACKJACK!
The dealer is showing a 5
You have a ['A', 8] for a total of 19
Do you want to [H]it, [S]tand, or [Q]uit: S
The dealer has a [5, 4, 7] for a total of 16
You have a ['A', 8] for a total of 19
Congratulations. Your score is higher than the dealer. You win
Do you want to play again? (Y/N) :
Also pasting here the indented code:
import os
import random
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
def deal(deck): # deck function
hand = []
for i in range(2):
random.shuffle(deck) # shuffles deck
card = deck.pop() # removes and returns the value back to card
if card == 11:
card = "J" # sets 11 to jack
if card == 12:
card = "Q" # sets 12 to queen
if card == 13:
card = "K" # sets 13 to king
if card == 14:
card = "A" # sets 14 to ace
hand.append(card)
return hand
def play_again(): # ask payer if wants to play again function
again = raw_input("Do you want to play again? (Y/N) : ").lower()
if again == "y": # if answers yes, will give the player more cards
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4 #sets deck to values of cards
game()
else:
print ("Bye!") # exits program
exit()
def total(hand):
total = 0 # start off with total of zero
for card in hand: # for the cards you dealt
if card == "J" or card == "Q" or card == "K": # if the card is j,q,k it equals 10
total += 10
elif card == "A":
if total >= 11:
total+= 1 # if the card is an A, if the total is more than 11, it makes the vaue 1
else:
total += 11 # makes the value of the ace 1 if the total is greater than 11
else:
total += card # adds up your cards
return total
def hit(hand):
card = deck.pop() # removes and returns the value back to card
if card == 11:
card = "J" # setting the card number to the face value
if card == 12:
card = "Q"
if card == 13:
card = "K"
if card == 14:
card = "A"
hand.append(card)
return hand
def clear():
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
def print_results(dealer_hand, player_hand): # funtcion for results of hand
clear()
print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand))) # gives you dealers hand
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # gives you your hand
def blackjack(dealer_hand, player_hand):
if total(player_hand) == 21:
print_results(dealer_hand, player_hand) # prints dealers and your hand
print ("Congratulations! You got a Blackjack!\n")
play_again()
elif total(dealer_hand) == 21: # if hand is more than 21,
print_results(dealer_hand, player_hand) # prints out dealer and your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
play_again()
def score(dealer_hand, player_hand):
if total(player_hand) == 21: # if your hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations! You got a Blackjack!\n")
elif total(dealer_hand) == 21: # if dealer hand = 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry, you lose. The dealer got a blackjack.\n")
elif total(player_hand) > 21: # if your hand is greater than
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. You busted. You lose.\n")
elif total(dealer_hand) > 21: # if dealer hand is greater than 21
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Dealer busts. You win!\n")
elif total(player_hand) < total(dealer_hand): # if your hand is less than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Sorry. Your score isn't higher than the dealer. You lose.\n")
elif total(player_hand) > total(dealer_hand): # if your hand is higher than the dealers
print_results(dealer_hand, player_hand) # shows dealers/ your hand
print ("Congratulations. Your score is higher than the dealer. You win\n")
def game():
choice = 0
clear()
print ("WELCOME TO BLACKJACK!\n") # welcomes player to game
dealer_hand = deal(deck) # deals to dealers
player_hand = deal(deck) # deals to player
while choice != "q":
print ("The dealer is showing a " + str(dealer_hand[0])) # shows what one of the dealers card is
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand))) # shows you your hand
blackjack(dealer_hand, player_hand) # send inormation to blackjack funciton
choice = raw_input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower() # gets user input on if they want to hit, stand, or quit
clear()
if choice == "h":
hit(player_hand) # adds a new card value to your exisiting han d
while total(dealer_hand) < 17: # dealer has to hit is value of cards below 17
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "s":
while total(dealer_hand) < 17:
hit(dealer_hand)
score(dealer_hand, player_hand)
play_again()
elif choice == "q":
print("Bye!")
exit()
if __name__ == "__main__":
game()
Let me know if this helped.

Blackjack, won't restart game in python

Right now I'm having trouble with the code restarting. It restarts but it doesn't go back to the beginning. It just keeps asking me if I want to restart.
For example it says
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
I type in Y and it keeps saying
The player has cards [number, number, number, number, number] with a total value of (whatever the numbers add up too.)
--> Player is busted!
Start over? Y/N
Can anyone please fix it so that it will restart. - or tell me how to my code is below.
from random import choice as rc
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
def total(hand):
# how many aces in the hand
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
if t > 21 and aces > 0:
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
c2win = 0 # computer2 win
cwin = 0 # computer win
pwin = 0 # player win
while True:
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
c2bust = False # computer2 busted
while True:
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
print('Start over? Y/N')
answer = input()
if answer == 'n':
done = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
print("do you want to play again?")
answer = input()
if answer == 'y':
done = False
else:
break
else:
hs = input("Hit or Stand/Done (h or s): ").lower()
if 'h' in hs:
player.append(rc(cards))
if 's' in hs:
player.append(rc(cards))
while True:
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
comp2 = []
comp.append(rc(cards))
comp.append(rc(cards))
while True:
tc = total(comp)
if tc < 18:
comp.append(rc(cards))
else:
break
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
if pbust == False:
print ("Player wins!")
pwin += 1
print('Start over? Y/N')
answer = input()
if answer == 'y':
playAgain()
if answer == 'n':
done = True
elif tc > tp:
print ("Computer wins!")
cwin += 1
elif tc == tp:
print ("It's a draw!")
elif tp > tc:
if pbust == False:
print ("Player wins!")
pwin += 1
elif cbust == False:
print ("Computer wins!")
cwin += 1
break
print
print ("Wins, player = %d computer = %d" % (pwin, cwin))
exit = input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print
print
print ("Thanks for playing blackjack with the computer!")
fun little game, I removed the second dealer for simplicity, but it should be easy enough to add back in. I changed input to raw_input so you could get a string out of it without entering quotes. touched up the logic a bit here and there, redid formating and added comments.
from random import choice as rc
def play_again():
"""This function returns True if the player wants to play again,
otherwise it returns False."""
return raw_input('Do you want to play again? (yes or no)').lower().startswith('y')
def total(hand):
"""totals the hand"""
#special ace dual value thing
aces = hand.count(11)
t = sum(hand)
# you have gone over 21 but there is an ace
while aces > 0 and t > 21:
# this will switch the ace from 11 to 1
t -= 10
aces -= 1
return t
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
cwin = 0 # computer win
pwin = 0 # player win
while True:
# Main Game Loop (multiple hands)
pbust = False # player busted
cbust = False # computer busted
# player's hand
player = []
player.append(rc(cards))
player.append(rc(cards))
pbust = False # player busted
cbust = False # computer busted
while True:
# Player Game Loop (per hand)
tp = total(player)
print ("The player has cards %s with a total value of %d" % (player, tp))
if tp > 21:
print ("--> Player is busted!")
pbust = True
break
elif tp == 21:
print ("\a BLACKJACK!!!")
break
else:
hs = raw_input("Hit or Stand/Done (h or s): ").lower()
if hs.startswith('h'):
player.append(rc(cards))
else:
break
#Dealers Hand
comp = []
comp.append(rc(cards))
comp.append(rc(cards))
tc = total(comp)
while tc < 18:
# Dealer Hand Loop
comp.append(rc(cards))
tc = total(comp)
print ("the computer has %s for a total of %d" % (comp, tc))
if tc > 21:
print ("--> Computer is busted!")
cbust = True
# Time to figure out who won
if cbust or pbust:
if cbust and pbust:
print ("both busted, draw")
elif cbust:
print ("Player wins!")
pwin += 1
else:
print ("Computer wins!")
cwin += 1
elif tc < tp:
print ("Player wins!")
pwin += 1
elif tc == tp:
print ("It's a draw!")
else:
print ("Computer wins!")
cwin += 1
# Hand over, play again?
print ("\nWins, player = %d computer = %d" % (pwin, cwin))
exit = raw_input("Press Enter (q to quit): ").lower()
if 'q' in exit:
break
print ("\n\nThanks for playing blackjack with the computer!")

Categories