Variables not being detected in blackjack program in Python - python

I wrote the following program to play blackjack with the user, but whenever a player gets a Jack, Queen, or King, the if statements in the total_value function do not detect them. What should I do to fix this? Also, do you have any general pointers to clean up my code or make my syntax better?
import random
from random import randint
class deck():
"""This class holds the deck information"""
clubs = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
spades = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
hearts = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
diamonds = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"]
suites = ["clubs", "spades", "hearts", "diamonds"]
def drawcard(self):
#This method removes a card from the deck and returns it.
#Do not draw cards when there are none left.
if self.suites:
suite = random.choice(self.suites)
suite_number = randint(0, len(self.suites) - 1)
if suite == "clubs":
card = (self.clubs).pop(randint(0, len(self.clubs) - 1))
if not self.clubs:
(self.suites).remove("clubs")
elif suite == "spades":
card = (self.spades).pop(randint(0, len(self.spades) - 1))
if not self.spades:
(self.suites).remove("spades")
elif suite == "hearts":
card = (self.hearts).pop(randint(0, len(self.hearts) - 1))
if not self.hearts:
(self.suites).remove("hearts")
elif suite == "diamonds":
card = (self.diamonds).pop(randint(0, len(self.diamonds) - 1))
if not self.diamonds:
(self.suites).remove("diamonds")
return card, suite
else:
return "OUT", "CARDS ERROR"
def total_value(hand):
#This function returns the current total value of a player's hand.
#For example, ["A", "K"] would return 21.
value = 0
aces = 0
for card in hand:
if card == "A":
aces = aces + 1
elif card == "J":
value == value + 10
elif card == "Q":
value == value + 10
elif card == "K":
value == value + 10
else:
value = value + card
if aces == 1:
if value <= 10:
value = value + 11
elif value > 10:
value = value + 1
elif aces == 2:
if value <= 9:
value = value + 12
elif value > 9:
value = value + 2
elif aces == 3:
if value <= 8:
value = value + 13
elif value > 8:
value = value + 3
elif aces == 4:
if value <= 7:
value = value + 14
elif value > 7:
value = value + 4
return value
new_deck = deck()
player_hand = [ ]
card1 = new_deck.drawcard()
card2 = new_deck.drawcard()
print "You have drawn a " + str(card1[0]) + " of " + card1[1] + " and a " + str(card2[0]) + " of " + card2[1] + "!"
player_hand.append(card1[0])
player_hand.append(card2[0])
dealer_hand = [ ]
card3 = new_deck.drawcard()
card4 = new_deck.drawcard()
dealer_hand.append(card3[0])
dealer_hand.append(card4[0])
gameover = False
win = False
dealer_finished = False
player_finished = False
while not gameover:
while dealer_finished == False:
if total_value(dealer_hand) < 17:
card = new_deck.drawcard()
dealer_hand.append(card[0])
elif total_value(dealer_hand) >= 17:
dealer_finished = True
if total_value(dealer_hand) > 21:
print "Dealer Busts!"
win = True
gameover = True
break
while player_finished == False:
choice = raw_input("Hit or Stay? ")
choice.capitalize()
if choice == "Hit":
card = new_deck.drawcard()
player_hand.append(card[0])
print "You drew a", card[0], "of " + card[1]
if total_value(player_hand) > 21:
player_finished = True
break
elif choice == "Stay":
player_finished = True
gameover = True
break
else:
print "Invalid Option"
if total_value(player_hand) > 21:
win == False
gameover == True
break
gameover == True
if win == True:
print "Congratulations!"
else:
print total_value(player_hand), total_value(dealer_hand)
if total_value(player_hand) > 21:
print "You bust!"
elif total_value(dealer_hand) > total_value(player_hand):
print "The dealer had", str(total_value(dealer_hand)), "but you only had", str(total_value(player_hand)) + "."
print "You lose!"
elif total_value(dealer_hand) == total_value(player_hand):
print "You tie the dealer with", total_value(dealer_hand)
elif total_value(dealer_hand) < total_value(player_hand):
print "The dealer had", str(total_value(dealer_hand)), "and you had", str(total_value(player_hand)) + ", so you win!"

You have double-equals signs for the J, Q, and K cases:
if card == "A":
aces = aces + 1
elif card == "J":
value == value + 10 #xxx
elif card == "Q":
value == value + 10 #xxx
elif card == "K":
value == value + 10 #xxx
else:
value = value + card
All this does is check whether value is value + 10 and evaluate to True or False. You want to assign the value:
if card == "A":
aces = aces + 1
elif card == "J":
value = value + 10
elif card == "Q":
value = value + 10
elif card == "K":
value = value + 10
else:
value = value + card
or better yet:
if card == "A":
aces = aces + 1
elif card == "J":
value += 10
elif card == "Q":
value += 10
elif card == "K":
value += 10
else:
value += card

Related

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

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']:

Why Spyder will not run or debug my code?

I am a beginner programmer using Python 3.7 on Spyder, and when i run my code, it opens a system32 command prompt that immediately closes afterward. Nothing happens. The same thing happens when I try to press the debug button. I'll paste my code here.
Edit: Thanks to oliverm, I have updated the code, but the code still will not start.
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#imports
import random
#def the vars
credits = 10
playagain = None
jack = 10
queen = 10
king = 10
ace = 11 #Nice
x = 0
y = 0
a = 0
b = 5
playing = True
cardamount = 0
deck = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,jack,jack,jack,jack,queen,queen,queen,queen,king,king,king,king,ace,ace,ace,ace]
#def the functions
def greetings():
print("Greetings! Weclome to Blackjack! d\Do you wish to play?")
print ("Yes or No")
answer = input()
if answer == "Yes" or "yes" or "y" or "Y":
blackjack()
elif answer == "No" or "no" or "n" or "N":
print ("Alright then. Have a good day!")
else:
print("I have no idea what you just said. can you try that again?")
return
def bets():
print ("How much will you bet?")
print ("You have ",credits, " credits")
bet = int(input())
print ("Alright! Lets start!")
pass
def playerplay():
card1 = random.choice(deck)
card2 = random.choice(deck)
#ace logic here. an if statement.
cardlist = [card1, card2]
if card1 == ace and card2 == ace:
pastace = 2
card1 = 1
card2 =11
elif card1 == ace:
pastace = 1
if card2 + 11 > 21:
ace = 1
else:
ace = 11
elif card2 == ace:
pastace = 1
if card1 + 11 > 21:
ace = 1
else:
ace = 11
else:
pastace = 0
pass
cardamount = card1 + card2
print ("You drew a ", card1, " and a ", card2)
while playing == True:
print ("You currently have ", cardamount, " points with ", pastace, "aces" )
print ("Hit or Stand?")
hvalue = str(input())
if hvalue == 'Hit' or "hit" or "H" or "h":
cardlist.append(random.choice(deck))
#calculates cardamount
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
#paste ace logic here
if cardlist[x + 1] == ace:
pastace += 1
if cardamount > 21 and pastace == 1:
ace = 1
cardamount == card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
print("You have drawn over 21 cards. Now the dealer will play.")
playing = False
del cardlist[0:x]
pcardamount = cardamount
pastace = 0
x = 0
pass
else:
x += 1
return
elif cardamount > 21 and pastace > 1:
ace = 1
cardamount = card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
print("You have drawn over 21 cards. Now the dealer will play.")
playing = False
del cardlist[0:x]
pastace = 0
pcardamount = cardamount
x = 0
pass
elif cardamount - 22 > -11:
ace in cardlist = 11
return
else:
x += 1
return
else:
x += 1
return
elif hvalue == 'Stand' or 'stand' or 'S' or "s":
print ('Alright! Your total card amount is ', cardamount)
playing = False
del cardlist[0:x]
pastace = 0
pcardamount = cardamount
x = 0
pass
else:
print ("I'm sorry. What did you say?")
return
def outcome():
print("Your total card amount was", pcardamount, "and the dealer's was ", dcardamount)
if pcardamount > dcardamount and pcardamount <= 21 :
print("You win!")
credits += bet*2
elif pcardamount < dcardamount and dcardamount <=21 :
print("You lose...")
credits -= bet
else:
print("It's a tie!")
#says who wins here and defines playagain
playing = True
print("You now have ", credits, " credits.")
print ("Do you wish to play again?")
answer2 = str(input())
if answer2 == "Yes" or "yes" or "y" or "Y":
blackjack()
elif answer2 == "No" or "no" or "n" or "N":
print("Thank you for playing! Have a great day!")
else:
print: ("I have no idea what you just said. can you try that again?")
return
def hit():
cardlist.append(random.choice(deck))
#calculates cardamount
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
#paste ace logic here
if cardlist[x + 1] == ace:
pastace += 1
if cardamount > 21 and pastace == 1:
ace = 1
cardamount == card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
else:
x += 1
return
elif cardamount > 21 and pastace > 1:
ace = 1
cardamount = card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
playing = False
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
elif cardamount - 22 > -11:
ace in cardlist = 11
return
else:
x += 1
return
else:
x += 1
def dealerplay():
card1 = random.choice(deck)
card2 = random.choice(deck)
#ace logic here. an if statement.
cardlist = [card1, card2]
if card1 == ace and card2 == ace:
pastace = 2
card1 == 1
card2 ==11
elif card1 == ace:
pastace = 1
if card2 + 11 > 21:
ace = 1
else:
ace = 11
elif card2 == ace:
pastace = 1
if card1 + 11 > 21:
ace = 1
else:
ace = 11
else:
pastace = 0
pass
cardamount = card1 + card2
if cardamount < 17:
hit()
return
else:
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
def blackjack():
bets()
playerplay()
dealerplay()
outcome()
#game functions put together
greetings()
Regarding:
'inconsistent use of tabs in indentation.'
You'll need to make sure to either use tabs OR simple space as white space characters. Mixing both will result in the error above. You can configure your spyder to use e.g. 4 intends when pressing tab.
As per the answer of Spyder Python indentation
try
In Spyder v3.0.0, go to Source --> Fix Indentation. That worked for me.
Before you can start debugging you need to fix your syntactic errors.
To use the debugger you'll need to define a breakpoint within your code or when starting the debugger. Spyder uses the ipdb debugger within the ipython console. Have a look at the spyder docs about debugging:
https://docs.spyder-ide.org/debugging.html
From their docs you have the following options to set a breakpoint:
Multiple means of setting and clearing normal and conditional breakpoints for any line in a file opened in the Editor.
By selecting the respective option from the Debug menu.
Through pressing a configurable keyboard shortcut (F12 for normal, or Shift-F12 for conditional breakpoints by default).
By double-clicking to the left of the line number in an open file.
With an ipdb.set_trace() statement in your code (after import ing pdb).
Interactively, using the b command in an ipdb session.
Have a look at e.g.:https://realpython.com/python-debugging-pdb/ for a quick debugging tutorial.
I've quickly fixed your syntactic problems in the code below. In addition, the if clause for choosing to play or not to play are changed to correctly evaluated to True or False if input is passed.
Debugging should now be possible. To get you started I've imported the ipdb at the beginning of your script and set a breakpoint in the greetings function (line 29).
Regarding your problem with the window closing, check what is set in Tools -> Preferences -> Run -> Console. If you want the program to execute in the current iPython console of Spyder select "Execute in current console".
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#imports
import random
import ipdb
#def the vars
credits = 10
playagain = None
jack = 10
queen = 10
king = 10
ace = 11 #Nice
x = 0
y = 0
a = 0
b = 5
playing = True
cardamount = 0
deck = [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,jack,jack,jack,jack,queen,queen,queen,queen,king,king,king,king,ace,ace,ace,ace]
# def the functions
def greetings():
ipdb.set_trace()
print("Greetings! Weclome to Blackjack! \n Do you wish to play?")
print("Yes or No")
answer = input()
if answer in ["Yes", "yes", "y", "Y"]:
blackjack()
elif answer in ["No", "no", "n", "N"]:
print("Alright then. Have a good day!")
return
else:
print("I have no idea what you just said. can you try that again?")
return
def bets():
print("How much will you bet?")
print("You have ", credits, " credits")
bet = int(input())
print("Alright! Lets start!")
return bet
def playerplay():
card1 = random.choice(deck)
card2 = random.choice(deck)
#ace logic here. an if statement.
cardlist = [card1, card2]
if card1 == ace and card2 == ace:
pastace = 2
card1 = 1
card2 =11
elif card1 == ace:
pastace = 1
if card2 + 11 > 21:
ace = 1
else:
ace = 11
elif card2 == ace:
pastace = 1
if card1 + 11 > 21:
ace = 1
else:
ace = 11
else:
pastace = 0
pass
cardamount = card1 + card2
print ("You drew a ", card1, " and a ", card2)
while playing == True:
print ("You currently have ", cardamount, " points with ", pastace, "aces" )
print ("Hit or Stand?")
hvalue = str(input())
if hvalue == 'Hit' or "hit" or "H" or "h":
cardlist.append(random.choice(deck))
#calculates cardamount
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
#paste ace logic here
if cardlist[x + 1] == ace:
pastace += 1
if cardamount > 21 and pastace == 1:
ace = 1
cardamount == card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
print("You have drawn over 21 cards. Now the dealer will play.")
playing = False
del cardlist[0:x]
pcardamount = cardamount
pastace = 0
x = 0
pass
else:
x += 1
return
elif cardamount > 21 and pastace > 1:
ace = 1
cardamount = card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
print("You have drawn over 21 cards. Now the dealer will play.")
playing = False
del cardlist[0:x]
pastace = 0
pcardamount = cardamount
x = 0
pass
elif cardamount - 22 > -11:
ace in cardlist == 11
return
else:
x += 1
return
else:
x += 1
return
elif hvalue == 'Stand' or 'stand' or 'S' or "s":
print ('Alright! Your total card amount is ', cardamount)
playing = False
del cardlist[0:x]
pastace = 0
pcardamount = cardamount
x = 0
pass
else:
print ("I'm sorry. What did you say?")
return
def outcome():
print("Your total card amount was", pcardamount, "and the dealer's was ", dcardamount)
if pcardamount > dcardamount and pcardamount <= 21 :
print("You win!")
credits += bet*2
elif pcardamount < dcardamount and dcardamount <=21 :
print("You lose...")
credits -= bet
else:
print("It's a tie!")
#says who wins here and defines playagain
playing = True
print("You now have ", credits, " credits.")
print ("Do you wish to play again?")
answer2 = str(input())
if answer2 in ["Yes", "yes", "y", "Y"]:
blackjack()
elif answer2 in ["No", "no", "n", "N"]:
print("Alright then. Have a good day!")
return
else:
print("I have no idea what you just said. can you try that again?")
return
def hit():
cardlist.append(random.choice(deck))
#calculates cardamount
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
#paste ace logic here
if cardlist[x + 1] == ace:
pastace += 1
if cardamount > 21 and pastace == 1:
ace = 1
cardamount == card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
else:
x += 1
return
elif cardamount > 21 and pastace > 1:
ace = 1
cardamount = card1 + card2
for y in len(cardlist):
cardamount += cardlist[y]
if y == len(cardlist):
y = 0
break
else:
y += 1
if cardamount > 21:
playing = False
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
elif cardamount - 22 > -11:
ace in cardlist == 11
return
else:
x += 1
return
else:
x += 1
def dealerplay():
card1 = random.choice(deck)
card2 = random.choice(deck)
#ace logic here. an if statement.
cardlist = [card1, card2]
if card1 == ace and card2 == ace:
pastace = 2
card1 == 1
card2 ==11
elif card1 == ace:
pastace = 1
if card2 + 11 > 21:
ace = 1
else:
ace = 11
elif card2 == ace:
pastace = 1
if card1 + 11 > 21:
ace = 1
else:
ace = 11
else:
pastace = 0
pass
cardamount = card1 + card2
if cardamount < 17:
hit()
return
else:
del cardlist[0:x]
pastace = 0
x = 0
dcardamount = cardamount
cardamount = 0
pass
def blackjack():
bets()
playerplay()
dealerplay()
outcome()
#game functions put together
greetings()

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.

Code execution shell vs Jupyter Notebook

I have a general question regarding code execution. I have a case when the same code is executed perfectly in shell and has some issues in Jupiter.
In Jupyter Notebook it tends to stop, usually at the beginning of the loop or before user input. Nothing happens then but the kernel is busy. Same part of the code sometimes works and sometimes doesn't.
Program is very simple so that should not be an issue. Have you ever faced similar issues? Can it be because I haven't split the code into few cells? Many thanks in advance!
EDIT: I've added the full code as I haven't managed to re-create a problem on a smaller sample. Basically the problem occurs either at the very start of the game when hit_or_stand should be executed or at the repeat_game() function level.
# import
import random
# define classes
deck_colors = ["Hearts", "Spades", "Clubs", "Diamonds"]
deck_ranks = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
deck_values = {"Two" : 2, "Three" : 3, "Four" : 4, "Five" : 5, "Six" : 6, "Seven" : 7, "Eight" : 8, "Nine" : 9,
"Ten" : 10, "Jack" : 10, "Queen" : 10, "King" : 10, "Ace" : 11}
class Card():
def __init__(self, color, rank):
self.color = color
self.rank = rank
self.value = deck_values[rank]
def __str__(self):
return self.rank + ' of ' + self.color
class Deck():
def __init__(self):
self.deck = []
for color in deck_colors:
for rank in deck_ranks:
self.deck.append(Card(color, rank))
def __str__(self):
deck_description = ''
for card in self.deck:
deck_description += card.__str__() + '\n'
return "\nCurrent deck:\n" + deck_description
#shuffle deck before the game
def shuffle(self):
random.shuffle(self.deck)
# pop last card to pass it on to players
def pop_card(self):
return self.deck.pop()
class Hand():
def __init__(self, name):
self.cards_in_hand = []
self.value = 0
self.aces = 0
self.name = name
def add_card(self, deck):
new_card = deck.pop_card()
self.cards_in_hand.append(new_card)
self.value += new_card.value
if new_card.rank == "Ace":
self.aces += 1
while self.aces > 0:
if self.value > 21:
self.value -= 10
self.aces -=1
else:
break
class Chips():
def __init__(self):
self.value = 100
self.bet = 0
def take_bet(self):
while True:
bet_value = input(f"You have {self.value} chips. What's your bet? ")
try:
bet_value = int(bet_value)
if bet_value > 0 and bet_value <= self.value:
self.bet = bet_value
self.value -= bet_value
break
elif bet_value > self.value:
print("You don't have enough chips.")
continue
else:
print(f"Choose correct value (1-{self.value})")
continue
except:
print(f"You have to choose correct number (1-{self.value})!")
def win_bet(self):
self.value += (self.bet * 2)
self.bet = 0
def lose_bet(self):
self.bet = 0
def draw(self):
self.value += self.bet
self.bet = 0
# define functions
def show_some_cards(player_hand, dealer_hand):
player_str = ''
for card in player_hand.cards_in_hand:
player_str += f"\n{card.__str__()} "
print("Player's cards:", player_str)
dealer_str = ' '
for card in dealer_hand.cards_in_hand[1:]:
dealer_str += f"\n{card.__str__()} "
print("\nDealer's cards:\n<hidden card>", dealer_str)
def show_all_cards(player_hand, dealer_hand):
player_str = ''
for card in player_hand.cards_in_hand:
player_str += f"\n{card.__str__()} "
print("Player's cards:", player_str)
print("Cards value:", player_hand.value)
dealer_str = ' '
for card in dealer_hand.cards_in_hand:
dealer_str += f"\n{card.__str__()} "
print("\nDealer's cards:", dealer_str)
print("Cards value:", dealer_hand.value)
def hit_or_stand(player1_hand, player2_hand, deck, chips):
global dealer_action
global busted_before
while True:
print('\n'*100)
print("Here're the cards\n")
show_some_cards(player1_hand, player2_hand)
action = input("Do you want another card? (Y/N)")
if action.upper() == "Y":
player1_hand.add_card(deck)
if player_hand.value > 21:
busted(player_hand, dealer_hand, chips)
dealer_action = False
busted_before = True
break
continue
elif action.upper() == "N":
break
else:
print("Choose correct answer (Y/N)")
continue
def dealer_playing(player1_hand, player2_hand, deck, chips):
global busted_before
while True:
print('\n'*100)
print("Here're the cards\n")
show_some_cards(player1_hand, player2_hand)
if player2_hand.value < 17:
player2_hand.add_card(deck)
if player2_hand.value > 21:
busted(dealer_hand, player_hand, chips)
busted_before = True
break
continue
else:
break
def busted(current_hand, other_hand, chips):
print('\n'*100)
if current_hand.name == "Player":
show_all_cards(current_hand, other_hand)
chips.lose_bet()
print(f"Player busted! You now have only {chips.value} chips.")
elif current_hand.name == "Dealer":
show_all_cards(other_hand, current_hand)
chips.win_bet()
print(f"Dealer busted! You now have {chips.value} chips.")
else:
print("Something went wrong! (busted function)")
def check_winners(player1_hand, player2_hand, chips):
print('\n'*100)
if player1_hand.value > player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.win_bet()
print(f"Player won! You now have {chips.value} chips.")
elif player1_hand.value < player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.lose_bet()
print(f"Dealer won! You now have only {chips.value} chips.")
elif player1_hand.value == player2_hand.value:
show_all_cards(player1_hand, player2_hand)
chips.draw()
print(f"It's a draw! You still have {chips.value} chips.")
def repeat_game(chips):
global repeat
while True:
repetition = input("Would you like to play again? (Y/N)")
if chips.value > 0:
if repetition.upper() == 'Y':
repeat = True
break
elif repetition.upper() == 'N':
repeat = False
break
else:
print("Choose correct value (Y/N)")
continue
else:
print("You don't'have enough chips to continue.")
repeat = False
break
def start_again():
global new_game
while True:
restart_game = input("Would you like to start completely new game? (Y/N)")
if restart_game.upper() == 'Y':
new_game = True
break
elif restart_game.upper() == 'N':
new_game = False
break
else:
print("Choose correct value (Y/N)")
continue
# play the game
new_game = True
while new_game == True:
repeat = True
player_chips = Chips()
print("Welcome to BlackJack!")
while repeat == True:
print('\n'*100)
#### initialization ###
current_deck = Deck()
current_deck.shuffle()
player_hand = Hand("Player")
player_hand.add_card(current_deck)
player_hand.add_card(current_deck)
dealer_hand = Hand("Dealer")
dealer_hand.add_card(current_deck)
dealer_hand.add_card(current_deck)
#### game_ongoing ###
player_chips.take_bet()
dealer_action = True
busted_before = False
hit_or_stand(player_hand, dealer_hand, current_deck, player_chips)
if dealer_action == True:
dealer_playing(player_hand, dealer_hand, current_deck, player_chips)
if busted_before == False:
check_winners(player_hand, dealer_hand, player_chips)
repeat_game(player_chips)
start_again()
Splitting the code in cells has nothing to do with the issue. Different cells are used so you won't run same code again and again. Notebook and shell have some small difference but the basic idea is same. you should share the notebook code, so, i can help you with your issue.

Python and global declaration

I'm having trouble trying to resolve this error:
SyntaxWarning: name 'meaning5' is assigned to before global declaration
Basically my program needs to allow the user to input their name, the program then calculates the users lucky number based on the assignment of a=1, b=2 etc.
This is my code so far:
from time import sleep
tempNumb = 0
tempLNN1a = 0
tempLNN1b = 0
tempLNN2a = 0
tempLNN2b = 0
varLNN1 = 0
varLNN2 = 0
LNN = 0
tempLNNa = 0
tempLNNb = 0
templetter = "nothing"
meaning1 = "Natural leader"
meaning2 = "Natural peacemaker"
meaning3 = "Creative and optimistic"
meaning4 = "Hard worker"
meaning5 = "Value freedom"
meaning6 = "Carer and a provider"
meaning7 = "Thinker"
meaning8 = "Have diplomatic skills"
meaning9 = "Selfless and generous"
global templetter
global tempNumb
global tempLNN1a
global tempLNN1b
global tempLNN2a
global tempLNN2b
global varLNN1
global varLNN1
global LNN
global tempLNNa
global tempLNNb
global meaning1
global meaning2
global meaning3
global meaning4
global meaning5
global meaning6
global meaning7
global meaning8
global meaning9
def mainprogram():
sleep(1)
print("-----------------------")
print("Welcome to LUCKY NAME \n NUMBERS")
print("-----------------------")
sleep(1)
firstname = input("Please input your first \nname in all capitals\n")
if firstname == firstname.upper():
print("-----------------------")
sleep(1)
surname = input("Please input your surname \nin all capitals\n")
if surname == surname.upper():
print("-----------------------")
print("Calculating your Lucky \nName Number...")
for i in range(len(firstname)):
templetter = firstname[i]
calculate()
tempfirstname()
for i in range(len(surname)):
templetter = surname[i]
calculate()
tempsurname()
finalcalculate()
def calculate():
if templetter == "A":
tempNumb = 1
elif templetter == "B":
tempNumb = 2
elif templetter == "C":
tempNumb = 3
elif templetter == "D":
tempNumb = 4
elif templetter == "E":
tempNumb = 5
elif templetter == "F":
tempNumb = 6
elif templetter == "G":
tempNumb = 7
elif templetter == "H":
tempNumb = 8
elif templetter == "I":
tempNumb = 9
elif templetter == "J":
tempNumb = 1
elif templetter == "K":
tempNumb = 2
elif templetter == "L":
tempNumb = 3
elif templetter == "M":
tempNumb = 4
elif templetter == "N":
tempNumb = 5
elif templetter == "O":
tempNumb = 6
elif templetter == "P":
tempNumb = 7
elif templetter == "Q":
tempNumb = 8
elif templetter == "R":
tempNumb = 9
elif templetter == "S":
tempNumb = 1
elif templetter == "T":
tempNumb = 2
elif templetter == "U":
tempNumb = 3
elif templetter == "V":
tempNumb = 4
elif templetter == "W":
tempNumb = 5
elif templetter == "X":
tempNumb = 6
elif templetter == "Y":
tempNumb = 7
elif templetter == "Z":
tempNumb = 8
else:
"You managed to break it."
mainprogram()
def tempfirstname():
varLNN1 = varLNN1 + tempNumb
def tempsurname():
varLNN2 = varLNN2 + tempNumb
def finalcalculate():
varLNN1 = str(varLNN1)
varLNN2 = str(varLNN2)
tempLNN1a = varLNN1[0]
tempLNN1b = varLNN1[1]
tempLNN2a = varLNN2[0]
tempLNN2b = varLNN2[1]
varLNN1 = int(tempLNN1a) + int(tempLNN1b)
varLNN2 = int(tempLNN2a) + int(tempLNN2b)
LNN = varLNN1 + varLNN2
LNN = str(LNN)
tempLNNa = LNN[0]
tempLNNb = LNN[1]
LNN = int(tempLNNa) + int(tempLNNb)
if LNN == 1 or "1":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning1)
loop()
elif LNN == 2 or "2":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning2)
loop()
elif LNN == 3 or "3":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are " + meaning3)
loop()
elif LNN == 4 or "4":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning4)
loop()
elif LNN == 5 or "5":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you " + meaning5)
loop()
elif LNN == 6 or "6":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning6)
loop()
elif LNN == 7 or "7":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are a " + meaning7)
loop()
elif LNN == 8 or "8":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you " + meaning8)
loop()
elif LNN == 9 or "9":
print("Your Lucky Name Number is - " + str(LNN) + " and it means you are " + meaning9)
loop()
else:
print("Somehow your lucky name number is too high...")
mainprogram()
Python is different than C, you don't have to declare a variable global, if you are using a global variable in a function, there you need to use global keyword.
For example:
meaning5 = "Value freedom"
def somefunction():
global meaning5
print meaning5
and as linsug has said use lists.
Simply define all the global variable in a single function like :
def global_variables():
global var_1
global var_2
global var_3
global var_4
.
global var_n
And before calling anything else in main, call this function first:
if __name__ == "__main__":
global_variables()
# Rest of your code.
Might it help!. Thanx

Categories