Why Spyder will not run or debug my code? - python

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()

Related

Why does choosemove() allow you to hit endlessly and not run lose() when the total value is greater then 21?

Is the code generating a new card every time choosemove() and then creating a new card again and adding on top if you hit again like its supposed to?
Basically, I need lose() to run when newtotalplayercardvalue > 21 so it shows the player lost, but it just lets you "hit" endlessly for some reason. Thanks in advance!
import random
def win():
print ("")
print("You won!")
menu()
def lose():
print ("")
print("You lost!")
menu()
def numbertocard(card):
if card == 11:
card = "J"
elif card == 12:
card = "Q"
elif card == 13:
card = "K"
elif card == 14:
card = "A"
else:
card = card
return card
def cardtonumber(cardvalue):
if cardvalue == "J":
cardvalue == 10
elif cardvalue == "Q":
cardvalue == 10
elif cardvalue == "K":
cardvalue = 10
elif cardvalue == "A":
cardvalue = 11
else: cardvalue = cardvalue
return (cardvalue)
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
newtotalplayercardvalue = newcard + totalplayercardvalue
if newtotalplayercardvalue > 21:
lose()
else:
choosemove()
def stand():
global totalplayercardvalue
global totaldealercardvalue
global dealercard2
print(f"The dealer's second card is a {dealercard2}")
if totalplayercardvalue > totaldealercardvalue:
win()
elif totaldealercardvalue > totalplayercardvalue:
lose()
def choosemove():
print("")
choice = input("Would you like to hit or stand? \n")
if choice == "hit":
hit()
elif choice == "stand":
stand()
else:
print("""Please only enter "hit" or "stand" """)
choosemove()
def startgame():
global totalplayercardvalue
global totaldealercardvalue
playercard1 = random.randint(1,14)
p_card1_name = numbertocard(playercard1)
print(f"Your first card is {p_card1_name}")
print("")
playercard2 = random.randint(1,14)
p_card2_name = numbertocard(playercard2)
print(f"Your second card is {p_card2_name}")
print("")
dealercard1 = random.randint(1,14)
d_card1_name = numbertocard(dealercard1)
dealercard2 = random.randint(1,14)
totalplayercardvalue = playercard2 + playercard2
totaldealercardvalue = dealercard1 + dealercard2
if totalplayercardvalue == 21 and totaldealercardvalue == 21:
tie()
elif totalplayercardvalue == 21:
win()
elif totaldealercardvalue == 21:
lose()
else:
print(f"The dealer's first card is a {d_card1_name}")
choosemove()
def menu():
play_game = input("Would you like to start a round? y/n: \n")
if play_game == "y":
startgame()
else:
print("""Say "y" """ )
menu()
menu()
First things first, your program isnt well formatted, there is no seperation between the way that global variables and local variables are defined. It's standard practice to define global variables in Uppercase. Will make life easier for you.
As to what the endless hitting is, you aren't updating the totalplayercard variable in hit. You just define newtotalplayercardvalue, check if that is greater than 21 else choosing move, it doesn't update the global variable instead try
def hit():
print("")
global totalplayercardvalue
newcard = random.randint(1,14)
new_card_name = numbertocard(newcard)
print(f"You got a {new_card_name}")
totalplayercardvalue += newcard
if totalplayercardvalue > 21:
lose()
else:
choosemove()
IDK how black jack works however this is the reason that I can see

The stay in blackjack python code doesnt work

There isnt a error in the code but when I run the code it doesn't do it the way I want it to
elif player == '-blackjack':
betted = int(input('how much would you like to gamble? : '))
your_card = random.randrange(2,21)
your_drawed = random.randrange(1,12)
opponent_card = random.randrange(2,21)
opponent_drawed = random.randrange(1,12)
if betted > player_money:
print('oye you dont have this much')
pass
elif betted <= player_money:
game = True
while game:
opponent_drawed = random.randrange(1,12)
your_drawed = random.randrange(1,12)
print(' ________________________________')
print('|Your total card : ' + str(your_card))
print('|Opponents total card : ?')
print('|h to hit, s to stay.')
player = input('|________________________________')
if opponent_card < 15:
opponent_card += opponent_drawed
elif opponent_card >= 15:
pass
if player == 'h':
your_card = your_card + your_drawed
if your_card > 21:
if opponent_card > 21:
print('BOTH BUSTED! tie')
game = False
elif opponent_card <= 21:
print('BUSTED! You lost ' + str(betted))
player_money -= betted
game = False
elif your_card == 21:
if opponent_card == 21:
print('Both 21! Tie')
game = False
elif opponent_card < 21 or opponent_card > 21:
print('You win! you won ' + str(betted))
player_money += betted
game = False
elif opponent_card > 21:
if your_card > 21:
print('man opponent busted tho, you should have stayed TIE!')
game = False
elif your_card <= 21:
print('opponent busted! you won ' + str(betted))
player_money += betted
game = False
elif player == 's':
if opponent_card == 21:
if your_card == 21:
print('both 21! tie!')
game = False
elif your_card < 21:
print('opponent reached 21 in this turn you lose ' + str(betted))
player_money -= betted
game = False
elif opponent_card > 21:
print('opponent busted you win ' + str(betted))
player_money += betted
game = False
When I run this code, the hit for blackjack works but the 's' button stay doesn't work
this happens when I try to stay, why does it do this? When I do hit it does successfully go up and everything works fine but just the stay part doesn't seem to be working
You need another conditional for the case where opponent_card < 21.

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.

why am i getting an UnboundLocalError after i add my while loop and if then else if statements?

Whats going on here?
It's a basic slot machine game but when i try and add my conditions for the coins and coin generating I get the UnboundLocalError.
The random numbers generate when i don't have my while loop and if then else if statements
import random
def main():
coins = 50
x = 0
y = 0
z = 0
while coins >= 0 or giveUp != yes:
coins = (coins - 3)
x = random.randrange(1, 7)
y = random.randrange(1, 7)
z = random.randrange(1, 7)
x = x
y = y
z = z
print (x + y + Z)
if (x == y) or (x == z):
if (x == 1):
coins = (coins + 3)
print ("you win 3 coins")
elif x == 2:
coins = (coins +3)
print = ("you win 3 coins")
elif x == 3:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 4:
coins = (coins +3)
print = ("you win 3 coins")
elif x == 5:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 6:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 7:
coins = (coins + 3)
print = ("you win 3 coins")
giveUp = (input("do you give up?"))
main()
This assignment (also called "binding")
giveUp = (input("do you give up?"))
means giveUp is a local.
The whileloop is trying to test this local variable before you have assigned to it (ie bound it)
You could fix this by setting giveUp = "No" before the while loop
Also the yes should probably be "yes"
while coins >= 0 or giveUp != yes:
In here your loop condition is up to a variable called giveUp, but you're trying to define that variable in the loop. You have to define it before the loop first. The best solution is define giveUp="No" before the while loop. Also input() returns string so it must be;
giveUp="No"
while coins >= 0 or giveUp != "yes":
#codes
Another tip, you're using or operator, so if user type no even without any coins user still can play. You should change it to and;
while coins >= 0 and giveUp != "yes":
Now if user want to play, need coins and 'yes'
Please correct your code...
print (x + y + Z) name Z in your code is Upper.
Sure error in here.. and print = name print should not follow the character =
Try this..
>>> import random
>>> def main():
coins = 50
x = 0
y = 0
z = 0
while coins >= 0 or giveUp != yes:
coins = (coins - 3)
x = random.randrange(1, 7)
y = random.randrange(1, 7)
z = random.randrange(1, 7)
x = x
y = y
z = z
print (x + y + z)
if (x == y) or (x == z):
if (x == 1):
coins = (coins + 3)
print ("you win 3 coins")
elif x == 2:
coins = (coins +3)
print ("you win 3 coins")
elif x == 3:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 4:
coins = (coins +3)
print ("you win 3 coins")
elif x == 5:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 6:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 7:
coins = (coins + 3)
print ("you win 3 coins")
giveUp = (input("do you give up?"))
>>> main()
you win 3 coins
do you give up?3
12
12
9
7
12
9
14
10
15
you win 3 coins
do you give up?1
9
>>>

Variables not being detected in blackjack program in 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

Categories