Python skipping elif statement - python

I'm trying to write a program that prints the values and keys in a dictionary depending of the input the user types. The problem appears when the elif statement on line 11 gets skipped. It doesn't matter if the if statement is false, the elif statement gets skipped. I'm learning so I don't really know where my error is. Thanks for the help!
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
print("Enter a conversion")
if input() == "Area Meassure":
displayConversion(areaM)
elif input() == "Linear Meassure":
displayConversion(linearM)
else:
print("Conversion not available")

Maybe this as the full code (too much inputss):
areaM = {str(1) + " acre" : str(160) + " sq rods"}
linearM = {str(1) + " ft" : str(12) + " in", str(1) + " yd": str(3) + " ft"}
def displayConversion(conv):
for k, v in conv.items():
print(str(v) + " = " + str(k))
while True:
a=input("Enter a conversion\n")
if a == "Area Meassure":
displayConversion(areaM)
break
elif a == "Linear Meassure":
displayConversion(linearM)
break
else:
print("Conversion not available")

Related

Hello, I'm trying to convert from YYYY/MM/DD to dd/mm/yyyy by using .strptime but it comes up with AttributeError: object has no attribute 'strptime'

from datetime import datetime
from datetime import date
import datetime
import time
import math
seconds_Yearly = 3656060*24
seconds_Daily = 606024
seconds_Hourly = 60*60
minute = 60
eventName1 = input("What is the name of the first event?")
print(" ")
eventName2 = input("What is the name of the second event?")
print(" ")
event_Year1 = input("Which year is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Month1 = input("Which month [1-12] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Day1 = input("Which day [1-31] is" + " " + str(eventName1) + " " + "in?")
print(" ")
event_Year2 = input("Which year is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Month2 = input("Which month [1-12] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Day2 = input("Which day [1-31] is" + " " + str(eventName2) + " " + "in?")
print(" ")
event_Year1 = int(event_Year1)
event_Month1 = int(event_Month1)
event_Day1 = int(event_Day1)
event_Year2 = int(event_Year2)
event_Month2 = int(event_Month2)
event_Day2 = int(event_Day2)
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
event1_date = event1_dates.strptime((event_Year1), (event_Month1), (event_Day1), "d/m/Y")
print(str(event1_date))
print(" ")
event2_date = date((event_Year2), (event_Month2), event_Day2)
print(event2_date)
print(" ")
seconds_event1 = time.mktime(event1_date.timetuple())
print(seconds_event1)
print(" ")
seconds_event2 = time.mktime(event2_date.timetuple())
print(seconds_event2)
print(" ")
seconds_difference_rough = seconds_event2 - seconds_event1
seconds_difference = abs(seconds_difference_rough)
print(seconds_difference)
print(" ")
minutes_difference = seconds_difference/60
print(minutes_difference)
print(" ")
hours_difference = minutes_difference/60
print(hours_difference)
print(" ")
days_difference_rough = hours_difference/24
days_difference = abs(days_difference_rough)
print(days_difference)
print(" ")
years_difference_roughs = seconds_difference/seconds_Yearly
years_difference_rough = seconds_difference//seconds_Yearly
years_difference = abs(years_difference_rough)
years_difference_remainer = seconds_difference%seconds_Yearly
print(years_difference)
print(years_difference_roughs)
weeks_difference_parta = (days_difference/7)/52
weeks_difference_partb = weeks_difference_parta/years_difference_roughs
weeks_difference = abs(weeks_difference_partb)
print(weeks_difference)
months_difference_part1a = hours_difference/24/30.435
months_difference_part1aa = months_difference_part1a//1
months_difference_part1b = abs(months_difference_part1aa)
print(months_difference_part1b)
months_difference_part2a = (years_difference * 12) - months_difference_part1b
month_difference_roughs = (years_difference * 12) - months_difference_part1a
months_difference_part2b = abs(months_difference_part2a)
days_decimal, whole = math.modf(months_difference_part1a)
print(" ")
print(months_difference_part2b)
print(" ")
print(months_difference_part1a)
print(" ")
days_difference1a = days_difference/28
days_difference1ab = days_difference/30.45
days_difference1b = days_difference1ab//1
days_difference1c = (days_difference1a - days_difference1ab)
days_difference_total = abs(days_difference1b)
print(days_difference_total)
print(" ")
print(days_difference1ab)
week_difference = days_difference_total/7
week_difference_total = abs(week_difference)
print(week_difference_total)
print(" ")
#hours_one = hours_difference
def days ():
global days, days_remaing_negative, days_remaing_positve, days_remaing
if event_Year2 > event_Year1:
months_difference_rough = days_difference/(hours_difference/24/30.435)
months_difference = abs(days_difference_rough)
months_difference_remainer = seconds_difference%seconds_Daily
print(months_difference)
print(days_decimal)
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
days_remaing = abs(days_remaing)
print(days_remaing)
else:
days_remaings = (days_decimal * 30.435) + 1
days_remaing = days_remaings//1
print(days_remaing)
def weeks():
global days_remaing, days, new_week, new_days2
if days_remaing >= 7:
new_weeks = days_remaing/7
abs_new_week = abs(new_weeks)
new_week = new_weeks//1
new_week_decimal, whole = math.modf(abs_new_week)
new_days1 = new_week_decimal * 7
new_days2 = new_days1//1
print(new_week)
print(new_days2)
else:
new_week = 0
new_days2 = days_remaing
print(new_days2)
def difference():
global new_days2, new_week, months_difference_part1b, years_difference, eventName1, eventName2, days_remaing, days, new_week, months_difference_part2b
if event_Year2 > event_Year1 or event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("a")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 > event_Month1:
print("b")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
elif event_Year2 == event_Year1 and event_Month2 == event_Month1 and event_Day2 > event_Day1:
print("C")
print(str(eventName1) + " "+ "is" + " " + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "before" + " " + str(eventName2))
else:
print("D")
print(str(eventName1) + " " + "is" + " " + "on" + " " + str(event1_date) + " " + " " + "which is" + str(years_difference) + "years" + " "+ str(months_difference_part2b
) + "months" + " " + str(new_week) + "weeks" + " " + str(new_days2) + "days" + " " + "After" + " " + " " + str(eventName2))
days ()
weeks()
difference()
Are you trying to convert event1_dates?
from datetime import date
event_Year1=2020
event_Month1=1
event_Day1=30
event1_dates = date((event_Year1), (event_Month1), (event_Day1))
print(event1_dates)
event1_date = event1_dates.strftime("%d/%m/%Y")
print(event1_date)
Output:
2020-01-30
30/01/2020

Iterating through owned ec2.snapshots [duplicate]

This question already has an answer here:
How to use boto3 to get a list of EBS snapshots owned by me?
(1 answer)
Closed 2 years ago.
Im trying to print out every snapshot that hasn't got the specific Tag "CostReference" inside my aws account.
To Iterate through the snapshots I'm using:
for snapshot in snapshots:
if(not costreferencetag_isset_snapshot(snapshot)):
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: No CostReferenceTag!! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + ": No CostReferenceTag\n"
count_snapshot += 1
continue
else:
costreference_snapshot = get_costreference_snapshot(snapshot)
if costreference_snapshot not in managedpsp:
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: The PSP: " + costreference_snapshot + " of: " + str(snapshot) + " is WRONG! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + " " + costreference_snapshot + ": Wrong PSP\n"
count_snapshot += 1
print(count_snapshot)
So far so good the code is working, but I'm also getting the public Snapshots that are owned by amazon, wich have no relevance for me.
Is there any way to filter those public snapshots?
Greets
Code for the other functions:
def costreference_isset(instance):
#Searching for Instance without CostReference-tags
if instance.tags is None:
print("[INFO]: No Tags have been set yet:")
return(False)
#Searching for CostReference-tags
for t in instance.tags:
if t['Key'] == 'CostReference':
return(True)
return(False)
def get_costreferencetag(instance):
for t in instance.tags:
if t['Key'] == "CostReference":
return(str(t['Value']))
return(False)
managedpsp is a list with valid Costreference - tags
Solved it with:
for snapshot in snapshots.filter(OwnerIds= ['self']):
if(not costreferencetag_isset_snapshot(snapshot)):
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: No CostReferenceTag!! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + ": No CostReferenceTag\n"
count_snapshot += 1
continue
else:
costreference_snapshot = get_costreference_snapshot(snapshot)
if costreference_snapshot not in managedpsp:
print("[SNAPSHOT] " + str(snapshot))
print("[INFO]: The PSP: " + costreference_snapshot + " of: " + str(snapshot) + " is WRONG! \n")
missingtagginginfo = missingtagginginfo + str(snapshot) + " " + costreference_snapshot + ": Wrong PSP\n"
count_snapshot += 1
print(count_snapshot)
Try using the filter owner-id with your own account number.
Check here for the CLI reference: describe-snapshots — AWS CLI Command Reference

How to get the next instance of an "ENDIF" string for if statement in custom language

I am making a custom language and writing it in Python. I have if statements with number equalities and inequalities, but I´m having trouble implementing the conditional execution of the code in the if statement block. Here's my code for the tokenizer of if statements:
elif tok == "IF":
tokens.append("IF")
tok = ""
elif tok == "THEN":
if expr != "" and isexpr == 0:
tokens.append("NUM:" + expr)
expr = ""
tokens.append("THEN")
tok = ""
I also use a string, "ENDIF", to end the if statement. Essentially, the "THEN" is the opening bracket and "ENDIF" is the closing bracket, if this was a language that used brackets.
The parser for int eq/ineq if statements:
elif toks[i] + " " + toks[i+1][0:3] + " " + toks[i+2] + " " + toks[i+3][0:3] + " " + toks[i+4] == "IF NUM LESSTHAN NUM THEN":
if toks[i+1][4:] < toks[i+3][4:]:
print("TRUE, " + toks[i+1][4:] + " is less than " + toks[i+3][4:])
else:
print("TRUE, " + toks[i+1][4:] + " is not less than " + toks[i+3][4:])
i += 5
elif toks[i] + " " + toks[i+1][0:3] + " " + toks[i+2] + " " + toks[i+3][0:3] + " " + toks[i+4] == "IF NUM MORETHAN NUM THEN":
if toks[i+1][4:] > toks[i+3][4:]:
print("TRUE, " + toks[i+1][4:] + " is greater than " + toks[i+3][4:])
else:
print("FALSE, " + toks[i+1][4:] + " is not greater than " + toks[i+3][4:])
i += 5
elif toks[i] + " " + toks[i+1][0:3] + " " + toks[i+2] + " " + toks[i+3][0:3] + " " + toks[i+4] == "IF NUM LESSOREQUAL NUM THEN":
if toks[i+1][4:] <= toks[i+3][4:]:
print("TRUE, " + toks[i+1][4:] + " is less than or equal to " + toks[i+3][4:])
else:
print("FALSE, " + toks[i+1][4:] + " is not less than or equal to " + toks[i+3][4:])
i += 5
elif toks[i] + " " + toks[i+1][0:3] + " " + toks[i+2] + " " + toks[i+3][0:3] + " " + toks[i+4] == "IF NUM MOREOREQUAL NUM THEN":
if toks[i+1][4:] >= toks[i+3][4:]:
print("TRUE, " + toks[i+1][4:] + " is greater than or equal to " + toks[i+3][4:])
else:
print("FALSE, " + toks[i+1][4:] + " is not greater than or equal to " + toks[i+3][4:])
i += 5
elif toks[i] + " " + toks[i+1][0:3] + " " + toks[i+2] + " " + toks[i+3][0:3] + " " + toks[i+4] == "IF NUM NOTEQUAL NUM THEN":
if toks[i+1][4:] != toks[i+3][4:]:
print("TRUE, " + toks[i+1][4:] + " is not equal to " + toks[i+3][4:])
else:
print("FALSE, " + toks[i+1][4:] + " is equal to " + toks[i+3][4:])
i += 5
here's an example of an if statement in my language:
IF 1 == 2 THEN
OUT "Hello, world!"
ENDIF
Obviously, that will return false, but it still prints Hello World as of now, because I don't know how to skip the code if it returns false... I was thinking of skipping to the next endif in the file... I think I know how to do it though. I just need to find the place of the token in the tokens[] array... if I can do that, then I can set the iterator variable past the ENDIF. Is there a function that will let me search an array for the next appearance of a string after a certain place (for example, tokens[4:]), then return the index value of that element in the array?
Thanks in advance!
I figured it out!
While it is very primitive and doesn't support nesting (yet), I have a simple solution to my problem. Basically, whenever it detects the 'IF' token, it loops through all of the tokens after that until it finds and 'ENDIF' token. While doing that, it increments an iterator called 'ii' and at the end, sets the main iterator past the 'ENDIF', ignoring the code within the if statement. This is only done if the condition parser returns false.
code:
def doIF_FALSE(tokens):
ii = 0
for token in tokens:
if token == "IF":
ii = 1
elif token == "ENDIF":
ii += 1
break
else:
ii += 1
return ii
for the call, I set the iterator value like this: i = doIF_FALSE(tokens[i:])
Example code:
IF 1 > 2 THEN
OUT "1 is greater than 2"
ENDIF
OUT "You passed the if statement"
Output:
"You passed the if statement"
NOTE: Yes, I realize that this is the same answer as another question I asked, but they're basically the same question...

Tic-Tac-Toe Game

I've wrote a code for the Tic-Tac-Toe game.
Here's what the code does:
Gets the name of Player 1.
Gets the name of Player 2.
Asks if the Player 1 wants X or O.
If he chooses X then Player 2 gets O and vice versa.
Prints the empty board.
Asks both players to enter the row and column one by one and prints the updated board.
If a player doesn't repeat previous player's spot, everything works fine until the end without any problem.
If a player repeats previous player's spot, a message is displayed saying that the previous player has already taken this spot and makes him guess again.
Now, after this point, if I guess any index other than the one that the previous player has already taken, it overwrites the previous players spot.
Screenshot of the terminal when this occurs:
I'm certain that the problem is in the function enterguess(turncount), but haven't been able to spot it yet. Any idea where the problem is?
<----------------------------------------------[ Demo Without the colors ]-------------------------------------------->
Code:
import termcolor
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
vb = termcolor.colored("|", "yellow", None, ['bold'])
s = termcolor.colored("\t+---+---+---+", "yellow", None, ['bold'])
players = {
'player1' : '',
'player2' : ''
}
sym = {
'player1': '',
'player2': ''
}
def rules ():
print("\nWelcome to Tic Tac Toe...")
def printboard():
#boardlist = [[" "," "," "],[" "," "," "],[" "," "," "]]
for row in board:
print s
print "\t" + vb + " " + row[0] + " " + vb + " " + row[1] + " " + vb + " " + row[2] + " " + vb
print s
def playerNames():
p1 = termcolor.colored(raw_input("\nEnter name of Player 1: ").title(), 'red', None, ['underline'])
p2 = termcolor.colored(raw_input("Enter name of Player 2: ").title(), 'blue', None, ['underline'])
sym['player1'] = termcolor.colored(raw_input("\n" + p1 + ', you want X or O? - ').capitalize(), 'red', None, ['bold'])
if sym['player1'] == 'X':
sym['player2'] = termcolor.colored('O', 'blue', None, ['bold'])
else:
sym['player2'] = termcolor.colored('X', 'red', None, ['bold'])
players['player1'] = p1
players['player2'] = p2
return {p1:termcolor.colored('X', 'red', None, ['bold']), p2: termcolor.colored('O', 'blue', None, ['bold'])}
def enterguess(turncount):
def guess(name):
return (int(input("\n" + players[name] + ", Enter row number: ")),
int(input(players[name] + ", Enter column number: ")))
if turncount % 2 == 0:
(row, col) = guess('player1')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player2'] + " already took that spot! Please guess again."
enterguess(turncount)
except:
print "\nPlease enter the indexes between 1 and 3."
enterguess(turncount)
else:
(row, col) = guess('player2')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player1'] + " already took that spot! Please guess again."
enterguess(turncount)
except IndexError:
print "\nPlease enter a number between 1 and 3."
enterguess(turncount)
return (row - 1, col - 1)
def changeboard(row, col, xo, c):
if c % 2 == 0:
board[row][col] = xo[players['player1']]
else:
board[row][col] = xo[players['player2']]
def checkWinner():
for x in range(3):
if board[x][0] == board[x][1] == board[x][2] and board[x][0] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[x][0]][0]
for y in range(3):
if board[0][y] == board[1][y] == board[2][y] and board[0][y] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[0][y]][0]
xx = 0
yy = 2
while True:
if board[xx][xx] == board[1][1] == board[2][yy] and board[xx][xx] != " ":
return [players[n] for n, s in sym.iteritems() if s == board[xx][xx]][0]
xx += 2
yy -= 2
if xx == 2:
break
def main():
rules()
xo = playerNames()
printboard()
turncount = 0
for turn in range(9):
(r, c) = enterguess(turncount)
print (r, c)
changeboard(r, c, xo, turncount)
turncount += 1
winner = checkWinner()
printboard()
if winner:
print("\nCongratulations " + winner + "! You are the winner.\n")
break
if turn == 8:
print ("\n Well! Its a tie.\n")
main()
The issue you have is that although you recall enterguess, you don't return it. So it simply keeps recalling enterguess until a valid input is given, then it just ignores all this and goes to the final return statement which still has the malformed guess.
Add return statements:
def enterguess(turncount):
def guess(name):
return (int(input("\n" + players[name] + ", Enter row number: ")),
int(input(players[name] + ", Enter column number: ")))
if turncount % 2 == 0:
(row, col) = guess('player1')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player2'] + " already took that spot! Please guess again."
return enterguess(turncount)
except:
print "\nPlease enter the indexes between 1 and 3."
return enterguess(turncount)
else:
(row, col) = guess('player2')
try:
if board[row - 1][col - 1] in [sym['player1'], sym['player2']]:
print "\n" + players['player1'] + " already took that spot! Please guess again."
return enterguess(turncount)
except IndexError:
print "\nPlease enter a number between 1 and 3."
return nterguess(turncount)
return (row - 1, col - 1)

trouble with classes in python

I am getting an error that reads this and no matter what I do I am unable to get rid of this code.
Traceback (most recent call last):
File "C:\Users\Ian\Desktop\BlackJack.py", line 226, in <module>
main()
File "C:\Users\Ian\Desktop\BlackJack.py", line 225, in main
blackjack.playgame()
File "C:\Users\Ian\Desktop\BlackJack.py", line 145, in playgame
self.firstround()
File "C:\Users\Ian\Desktop\BlackJack.py", line 83, in firstround
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
AttributeError: type object 'DeckofCards' has no attribute 'shuffledeck'
The following is the actual code that I have written ( I have changed a great deal in order to move the error along but can no longer figure out what is going on) I am really just want someone to skim over this and tell me about the obvious mistakes, I am sure there are many, and I apologize but our professor doesn't teach use how to do things and then just expects us to know how.
from random import*
class Card(object):
def __init__(self,suit,number):
self.suit=suit
self.number=number
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
#print(self.shuffledeck)
def shuffle(self):
#print('This is shuffle function')
b=[]
count=0
while count<len(self.deck):
a=randrange(0,len(self.deck))
if a not in b:
b.append(self.deck[a])
count+=1
return(b)
def deal(self):
if len(self.shuffledeck)>0:
return(self.shuffledeck.pop(0))
else:
shuffle(self)
return(self.shuffledeck.pop(0))
class Player(object):
def __init__(self,name,hand,inout,money,score,bid):
self.name=name
self.hand=hand
self.inout=inout
self.money=money
self.score=score
self.bid=bid
def __str__(self):
x = self.name + ":\t"
x += "Card(s):"
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
if (self.name != "dealer"):
x += "\t Money: $" + str(self.money)
return(x)
class Game(object):
def __init__(self,deck, player):
self.player=Player(player,[],True,100,0,0)
self.dealer=Player("Dealer",[],True,100,0,0)
self.deck=DeckofCards(deck)
self.blackjack= False #self.blackjacksearch()
def blackjacksearch(self):#this is where it says there is an error we moved this because she said it needed to be in this class to get the Getot function
if self.player.hand.gettot()==21:
return True
else:
return False
def firstround(self):
self.player.inout=True
self.player.hand=[]
self.dealer.hand=[]
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
print(a)
playerbid=int(input('How much would you like to bet?'))
self.player.bid=playerbid
def playturn(self):
while self.player.blackjack!=True or hit=='yes':
print(self.player.hand)
a=self.player.hand.append(deal())
print('The card that you just drew is ' + str(a))
print(gettot())
hit=input('Would you like to hit? ')
if hit=='yes':
return(self.player.hand.append(deal()))
else:
return() #might need to change this
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while self.dealer.hand<17:
self.dealer.hand.append(deal())
dealerhand=self.dealer.hand.gettot() #confused
print(dealerhand)
if self.dealer.hand==21:
self.dealer.blackhjack=True
dealerhand1=self.dealer.hand.gettot()
print(dealerhand1)
def gettot(self,hand):
total=0
for x in self.hand:
if x==Card('H','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('D','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('S','A'):
b=total+x
if b>21:
total+=1
else:
total+=11
if x==Card('C','A'):
if b>21:
total+=1
else:
total+=11
else:
total+=x
return(total)
def playgame(self):
play = "yes"
while (play.lower() == "yes"):
self.firstround()
self.playturn()
if self.player.blackjack == True:
print(self.player.name + " got BLACKJACK! ")
self.player.money += self.player.bid * 1.5
print (self.player.name + " now has " + str(self.player.money))
print("\n")
self.player.inout = False
if self.player.score > 21:
print(self.player.name + " lost with a tot of " + str(self.player.score))
self.player.money -= self.player.bid
print (self.player.name + " now has " + str(self.player.money))
print ("\n\n")
self.player.inout = False
self.playdealer()
if self.dealer.blackjack == True:
print("Dealer got blackjack, dealer wins\n")
self.player.money -= self.player.bid
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
elif self.player.inout == True:
print("Round\n")
print("\t",self.dealer)
print("\t",self.player)
print("\n\t Dealer has " + str(self.dealer.score) + ", " + self.player.name + " has " + str(self.player.score))
if self.dealer.score > 21:
print("\t Dealer lost with a total of " + str(self.dealer.score))
self.player.money += self.player.bid
print(self.player.name + " now has " + str(self.player.money))
elif self.player.score > self.dealer.score:
print("\t" +self.player.name + " won with a total of " + str(self.player.score))
self.player.money += self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("\t Dealer won with a total of " + str(self.dealer.score))
self.player.money -= self.player.bid
print("\t"+self.player.name + " now has " + str(self.player.money))
else:
print("Round")
print("\t",self.dealer)
print("\t",self.player)
if self.player.blackjack == False:
print("\t "+ self.player.name + " lost" )
else:
print("\t "+self.player.name + " Won!")
if self.player.money <= 0:
print(self.player.name + " out of money - out of game ")
play = "no"
else:
play = input("\nAnother round? ")
print("\n\n")
print("\nGame over. ")
print(self.player.name + " ended with " + str(self.player.money) + " dollars.\n")
print("Thanks for playing. Come back soon!")
ls= [Card('H','A'),Card('H','2'),Card('H','3'),Card('H','4'),Card('H','5'),Card('H','6'),Card('H','7'),Card('H','8'),Card('H','9'),Card('H','10'),
Card('H','J'),Card('H','Q'),Card('H','K'),
Card('S','A'),Card('S','2'),Card('S','3'),Card('S','4'),Card('S','5'),
Card('S','6'),Card('S','7'),Card('S','8'),Card('S','9'),Card('S','10'),
Card('S','J'),Card('S','Q'),Card('S','K'),
Card('C','A'),Card('C','2'),Card('C','3'),Card('C','4'),Card('C','5'),
Card('C','6'),Card('C','7'),Card('C','8'),Card('C','9'),Card('C','10'),
Card('C','J'),Card('C','Q'),Card('C','K'),
Card('D','A'),Card('D','2'),Card('D','3'),Card('D','4'),Card('D','5'),
Card('D','6'),Card('D','7'),Card('D','8'),Card('D','9'),Card('D','10'),
Card('D','J'),Card('D','Q'),Card('D','K')]
'''tom=Card('Heart','Queen')
print(tom.suit)
print(DeckofCards(ls))
print(ls.suit)'''
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()
This line right is one problem:
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
append returns None (regardless of what you append), so a will be None
DeckofCards refers to the class object, not an instance of the class. You probably want to use self.deck instead of DeckofCards.
x==Card('S','A'): isn't going to work either. You haven't defined __eq__ for the Card object, so comparisons don't work (you'll always get False).
The shuffledeck attribute only exists for instances of DeckOfCards, change DeckOfCards.shuffledeck to DeckOfCards().shuffledeck.
class Game(object):
def __init__(self,deck, player):
self.player=Player(player,[],True,100,0,0)
self.dealer=Player("Dealer",[],True,100,0,0)
self.deck=DeckofCards(deck)
self.blackjack= False #self.blackjacksearch()
def blackjacksearch(self):#this is where it says there is an error we moved this because she said it needed to be in this class to get the Getot function
if self.player.hand.gettot()==21:
return True
else:
return False
def firstround(self):
self.player.inout=True
self.player.hand=[]
self.dealer.hand=[]
a=self.dealer.hand.append(DeckofCards.deal(DeckofCards.shuffledeck))
You are using the class incorrectly. The DeckofCards was never created.
a=self.dealer.hand.append(self.deck.deal(self.deck.shuffledeck))

Categories