getting rid of 'NONE' before a print statement in python - python

Hi I am new to python and programming, I have written some code for a wordgame and when it runs,
there is a 'None' printed out before some output. is there a way to remove them, I know it has to do with the loop returning nothing but I would rather not have to change the code a lot if possible(took me long enough the first time :))
Thanks in advance.
def compPlayHand(hand, wordList, n):
# Keep track of the total score
totalScore = 0
# As long as there are still usable letters left in the hand:
while compChooseWord(hand,wordList,n) is not None:
# Display the hand
print "Current Hand: ",
print displayHand(hand),
word = compChooseWord(hand,wordList,n) # comp chooses word
hand = updateHand(hand,word)
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
getWordScore(word,n)
totalScore += getWordScore(word,n)
# Update the hand
c = calculateHandlen(hand)
print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points." # Otherwise (the word is valid):
print
if compChooseWord(hand,wordList,n) is None: # End the game (break out of the loop)
print "Current Hand: ", \
displayHand(hand),
print "Total score: " + str(totalScore) + " points."

We've been over this, don't print displayHand, just call it on its own.
def compPlayHand(hand, wordList, n):
# Keep track of the total score
totalScore = 0
# As long as there are still usable letters left in the hand:
while compChooseWord(hand,wordList,n) is not None:
# Display the hand
print "Current Hand: ",
displayHand(hand)
word = compChooseWord(hand,wordList,n) # comp chooses word
hand = updateHand(hand,word)
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
getWordScore(word,n)
totalScore += getWordScore(word,n)
# Update the hand
c = calculateHandlen(hand)
print '"'+str(word)+'"' + " earned " + str(getWordScore(word,n)) +' points.' " Total: " + str(totalScore) + " points." # Otherwise (the word is valid):
print
if compChooseWord(hand,wordList,n) is None: # End the game (break out of the loop)
print "Current Hand: ",
displayHand(hand)
print "Total score: " + str(totalScore) + " points."

Related

How can I get python to count the amount of characters of a word and then continue or stop the code?

For an assignment, I need to use the "len" function to determine how many characters were entered in the "original_word". If the word is greater than or less than five characters the program needs to "exit()"
How can I do this?
original_word: str = input("Enter a 5-character word: ")
character_one: str = input("Enter a single character: ")
print("Searching for " + character_one + " in " + original_word)
if character_one == original_word[0]:
print(character_one + " found at index 0")
if character_one == original_word[1]:
print(character_one + " found at index 1")
if character_one == original_word[2]:
print(character_one + " found at index 2")
if character_one == original_word[3]:
print(character_one + " found at index 3")
if character_one == original_word[4]:
print(character_one + " found at index 4")
counter = 0
for c in original_word:
if c == character_one:
counter += 1
if counter == 2:
print(counter, " instances of " + character_one + " found in " + original_word)
if counter == 1:
print(counter, " instance of " + character_one + " found in " + original_word)
if counter == 0:
print("No instances of " + character_one + " found in " + original_word)
The one of the possible ways is to make the function, which complete the code if the length of your word is 5, else it returns the phrase "Length is not 5, try again"
Also you can do that code a bit shorter.
Here is the example:
def main(original_word, character_one):
if len(original_word) == 5:
temp_word = original_word
print(f"Searching for {character_one} in {original_word}")
while True:
if character_one in temp_word:
index = temp_word.find(character_one)
print(f"{character_one} found at index {index}")
temp_word = temp_word[:index] + ' ' + temp_word[index + 1:]
else:
break
counter = original_word.count(character_one)
print(f"{counter} instances of {character_one} found in {original_word}")
else:
return "The input word is greater or less than 5 characters! Please, try again."
original_word: str = input("Enter a 5-character word: ")
character_one: str = input("Enter a single character: ")
if __name__ == "__main__":
main(original_word, character_one)
The first modification is f-string. This is the most popular and handy future of concatanation instead of summarizing variables and string.
The second modification is checking if the character is in word, instead of using a lot of if-statements. It is easy to check by:
if x in y:
The way to find the index of character in your string is method find. Sample:
string.find(substring) # It returns the index of substring in string
And the last one is method counter which returns the amount of substring in your string. This is the sample:
string.count(substring) # It returns amount of substring in your string

High score code not saving scores properly

I have this code as part of a larger dice game program to save the high score in a separate file (as well as the normal winning score file) but it always saves the highscore regardless whether it's higher or lower and also doesn't save it in the Winning_scores file either
It also saves it in the form of ('Name: ', 'John', 'Score: ', '10', '\n') instead of the variables separately because of the str because otherwise I get 'write() argument must be str, not tuple' which I'm also not quite sure how to fix
tot1 = 5
tot2 = 1
name1 = ('John')
while True: #Code to find & print the winner
if tot1 > tot2:
print("Player 1 is the winner!")
#Opens file & appends the winning score at the end of it
tot1 = str(tot1)#Turns the score into a str
win_score = open("Winning_scores.txt", "a")
winner = ("Name: "+name1+" Score: "+tot1)
win_score.write(winner)
win_score.write("\n")
win_score.close()
print("Score saved.")
hisc = open("Winning_scores.txt", "w+")
highscore = hisc.read()
highscore_in_no = (highscore)
highscore_in_no = highscore_in_no
if tot1 > highscore_in_no:
print("Exceeded high score.")
highscore_in_no = tot1
hiscore = open("High_scores.txt", "a")
winner = ("Name: ",name1,"Score: ",tot1,"\n")
hiscore.write(winner)
hiscore.close()
print("High score saved.")
break
your winner variable is a tuple, not a string.
in order to use hiscore.write(winner), winner should be a string as follows:
winner = "Name: " + name1 + "Score: " + tot1 + "\n"
or nicer readable:
winner = "Name: {name1} Score: {tot1}\n".format(**locals())
you can also join your existing winner tuple to a string:
hiscore.write(' '.join(winner))
This is your problem:
winner = ("Name: "+name1+" Score: "+tot1)
win_score.write(winner)
When you wrap a value in parenthesis in Python, you're saying it's a tuple, something sort of similar to a list. Here's a hopefully more clear example
one = "foo"
two = "bar"
this_is_a_tuple = (one, two)
this_is_also_a_tuple = (one)
this_is_not_a_tuple = one + two
this_is_a_tuple = (one + two)

Python 2.7.3 Code Loops Without a While Loop

I am relatively new to programming, so don't be surprised if there are some minor hiccups in the code, but the problem that is happening is that this code seems to loop itself, the whole thing and I don't understand why. I looked at the actual code that runs this function but it seemed fine. So I cannot find any error in this code that makes it loop itself. (If the problem isn't in this code then the looping code it beneath it)
def thebeast(yourhp):
foe = "Thisisirrelevant"
enemy = int(random.randint(1,4))
if enemy == 1:
foe = "skeleton"
elif enemy == 2:
foe = "man with crazy eyes"
else:
foe = "dog, a big and scary dog"
monsteract = 1
dmg = 0
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print " C O M B A T"
time.sleep(0.1)
print "-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~-=~"
time.sleep(0.1)
print "You encounter a " + foe
time.sleep(0.5)
while monsteract == 1:
comb = str(input("What do you do to the " + foe + "?" + " Do you feel like jabbing it or stabbing it?"))
if comb in ["s", "S", "Stab", "STAB", "stab"]:
if spear == 1:
dmg = int(random.randint(1,4))
elif sword == 1:
dmg = int(random.randint(1,3))
else:
dmg = int(random.randint(1,5))
elif comb in ["j", "J", "Jab", "JAB", "jab"]:
if spear == 1:
dmg = int(random.randint(1,3))
elif sword == 1:
dmg = int(random.randint(1,4))
else:
dmg = int(random.randint(1,5))
if dmg == 1:
print "You slay the " + foe + " with graceful ease"
time.sleep(0.5)
monsteract = 0
else:
enemydmg = int(random.randint(1,3))
print "The " + foe + " strikes you for " + str(enemydmg) + " damage"
time.sleep(0.3)
print "That didn't work out as planned, but you pull yourself together and prepare to strike the " + foe
time.sleep(0.3)
yourhp = yourhp - enemydmg
if yourhp < 0:
yourhp = 0
print "You have " + str(yourhp) + " health left"
time.sleep(0.3)
if yourhp < 1:
print "The " + foe + " has slain you, well done, you're dead, on the bright side the innocent "
print foe + " is still alive! Every life counts, even that of a " + foe + "."
monsteract = 0
return thebeast(yourhp)
Looping code:
def randomevents(yourhp):
turn = 10
while turn > 0:
time.sleep(0.1)
happening = int(random.randint(1,6))
time.sleep(0.1)
if yourhp < 1:
turn = 0
print "You managed to escape the dungeon, by dying that is"
elif happening == 1:
turn = turn - 1
thebeast(yourhp)
elif happening == 2:
item(sword, spear)
turn = turn - 1
elif happening in [3, 4, 5]:
friend()
turn = turn - 1
print "Well done! You escaped the dungeon! (Either by running out of it, or by having your soul sent to another world)"
useless = str(input("Are you satsified with yourself?: "))
Thank you!
Look at your return statement at the end of thebeast. At the end of the function, you call the function again! Since this happens every time you call it, you will never stop calling it (until you hit the maximum recursion depth). Considering that you don't capture the return value of thebeast in randomevents, you should consider it not returning anything.

Graph results using canvas in tkinter

I have written my code and I want to graph the amount of times each dice is rolled. This isn't working how can I do it. I don't want to use any graphing packages.
import random
import time
name="JORDAN SUMMERS RANDOM NUMBER GENERATOR ASSIGNMENT"
by="## Created by Jordan Summers ##"
date="# 31.03.2015"
symbol="_"*50
bos=""*5
warning = "Please enter a number, i.e. 1. Not 'one'."
information=""" YOU WILL CHOOSE HOW MANY TIMES TO ROLL THE DICE,
ONCE ROLLED THE PROGRAM WILL PRINT THE NUMBERS, THEN IT WILL SORT THE NUMBERS
HIGHEST TO LOWEST. """
print("{:^80}\n{:^80}\n{:^80}\n{:^80}\n{:^80}\n{}".format(name,by,date,warning,symbol,bos,))
rolllist = []
total = 0
dice = int(input("How many times do you want to roll the dice? "))
if dice >50:
print("Please enter a lower number")
else:
for i in range(dice):
rolllist.append (random.randint(1,6))
print ("You rolled a " + str(rolllist[i])) #Here we are adding the results to the list
total = sum(rolllist)
print ("The total of the numbers " + str(total)) #This is calculating the total
rolllist.sort()
print ("numbers sorted " + str(rolllist)) #This is sorting the numbers in order of value
a = rolllist.count(1)
print ("The number 1 occured " + str(a) + " times." + " It's percentage is ") #Line 34 to line 51 are counting how many times a number occured.
percent_1 = ((int(rolllist.count(1))/(dice)))
print(percent_1*100)
b = rolllist.count(2)
print ("The number 2 occured " + str(b) + " times." + " It's percentage is ")
percent_2 = ((int(rolllist.count(2))/(dice)))
print(percent_2*100)
c = rolllist.count(3)
print ("The number 3 occured " + str(c) + " times." + " It's percentage is ")
percent_3 = ((int(rolllist.count(3))/(dice)))
print(percent_3*100)
d = rolllist.count(4)
print ("The number 4 occured " + str(d) + " times." + " It's percentage is ")
percent_4 = ((int(rolllist.count(4))/(dice)))
print(percent_4*100)
e = rolllist.count(5)
print ("The number 5 occured " + str(e) + " times." + " It's percentage is ")
percent_5 = ((int(rolllist.count(5))/(dice)))
print(percent_5*100)
f = rolllist.count(6)
print ("The number 6 occured " + str(f) + " times." + " It's percentage is")
percent_6 = ((int(rolllist.count(6))/(dice)))
print(percent_6*100)
from tkinter import *
root = Tk()
canvas = Canvas(root, width = 640, height = 360, bg = "red")
canvas.pack()
canvas.create_rectangle(1, 360, 50,(a), fill = "black")
canvas.create_rectangle(60,360, 100,(b), fill = "blue")
canvas.create_rectangle(110,360, 150,(c), fill = "yellow")
canvas.create_rectangle(160,360, 200,(d), fill = "white")
canvas.create_rectangle(210,360, 250,(e), fill = "orange")
canvas.create_rectangle(260,360, 300,(f), fill = "pink")
root.mainloop()
What do I do. I want this to graph, what I'm doing should work. I don't understand.
Note: always write clearly what is the problem. Here, I lost some time finding what it was.
So your first reectangle has y-coordinates 360 and a. And a is always small.
Try something like:
canvas = Canvas(root, width = 640, height = 100, bg = "red")
canvas.create_rectangle(1, 100, 50,100 - percent_1 *100, fill = "black")

Trouble with printing out of Classes in Python

We are supposed to use the code below to print out the parameters listed in it, currently however we are unable to do so and are using a round about method. This is supposed to print out things instead of what we print out in the Game class in the playturn function
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)
Here is our actual code, if you also see any other issues your input would be greatly appreciated
from random import*
#do we need to address anywhere that all face cards are worth 10?
class Card(object):
def __init__(self,suit,number):
self.number=number
self.suit=suit
def __str__(self):
return '%s'%(self.number)
class DeckofCards(object):
def __init__(self,deck):
self.deck=deck
self.shuffledeck=self.shuffle()
def shuffle(self):
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
def blackjacksearch(self):
if Game.gettot(self.player.hand)==21:#changed
return True
else:
return False
def firstround(self):
#self.player.inout=True#do we need this since this is above
#self.player.hand=[]#do wee need this....
#self.dealer.hand=[]#do we need this ....
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print(self.player.name + ' ,you were dealt a '+str(a))
self.dealer.hand.append(DeckofCards.deal(self.deck))
for card in self.dealer.hand:
a=card
print('The Dealer has '+str(a))
playerbid=int(input(self.player.name + ' how much would you like to bet? '))
self.player.money-=playerbid
self.player.bid=playerbid
def playturn(self): #should this be changed to inout instead of hit.....we never use inout
#for player in self.player:
# a=player
#print(str(a))
hit=input('Would you like to hit? ') #should input be in loop?
while self.player.inout==True: #and self.blackjack!=True:#changed
print(self.player.name + ' , your hand has:' + str(self.player.hand)) #do we want to make this gettot? so it prints out the players total instead of a list....if we want it in a list we should print it with out brakets
self.player.hand.append(DeckofCards.deal(self.deck))
for card in self.player.hand:
a=card
print('The card that you just drew is: ' + str(a))
#print(Game.gettot(self.player.hand))
hit=input('Would you like to hit? ')
if hit=='yes':
(self.player.hand.append(DeckofCards.deal(self.deck)))#changed
self.player.inout==True#
else:
(self.player.hand) #changed
self.player.inout==False #changed
if self.player.blackjack==True:
print(self.player.name + " has blackjack ")
if hit=='no':
print (self.player.hand.gettot())
def playdealer(self):
while Game.gettot(self.dealer.hand)<17:#changed
self.dealer.hand.append(DeckofCards.deal(self.deck))
dealerhand=Game.gettot(self.dealer.hand) #changed
print(dealerhand)
if Game.gettot(self.dealer.hand)==21:#changed
self.dealer.blackhjack=True
dealerhand1=Game.gettot(self.dealer.hand)#changed
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'):
b=total+x #changed
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')]
def main():
x = input("Player's name? ")
blackjack = Game(ls,x)
blackjack.playgame()
main()
The problem is that, in at least some places, you're trying to print a list.
While printing anything, including a list, calls str on it, the list.__str__ method calls repr on its elements. (If you don't know the difference between str and rep, see Difference between __str__ and __repr__ in Python.)
If you want to print the str of every element in a list, you have to do it explicitly, with a map or list comprehension.
For example, instead of this:
print(self.player.name + ' , your hand has:' + str(self.player.hand))
… do this:
print(self.player.name + ' , your hand has:' + [str(card) for card in self.player.hand])
But this is still probably not what you want. You will get ['8', '9'] instead of [<__main__.Card object at 0x1007aaad0>, <__main__.Card object at 0x1007aaaf0>], but you probably wanted something more like `8H 9C'. To do that, you'd want something like:
print(self.player.name + ' , your hand has:' +
' '.join(str(card) for card in self.player.hand))
You already have similar (although more verbose) code inside Player.__str__:
for y in range(len(self.hand)):
x +=self.hand[y].face + self.hand[y].suit + " "
This code could be improved in a few ways.
First, it's going to raise an AttributeError because you're using face instead of number. But really, you shouldn't need to do this at all—the whole reason you created a Card.__str__ method is so you can just use str(Card), right?
Second, you almost never want to loop over range(len(foo)), especially if you do foo[y] inside the loop. Just loop over foo directly.
Putting that together:
for card in self.hand:
x += str(card) + " "
At any rate, you need to do the same thing in both places.
The version that uses the join method and a generator expression is a little simpler than the explicit loop, but does require a bit more Python knowledge to understand. Here's how you'd use it here:
x += " ".join(str(card) for card in self.hand) + " "
Your next problem is that Card.__str__ doesn't include the suit. So, instead of 8H 9C, you're going to get 8 9. That should be an easy fix to do on your own.
Meanwhile, if you find yourself writing the same code more than once, you probably want to abstract it out. You could just write a function that takes a hand list and turns it into a string:
def str_hand(hand):
return " ".join(str(card) for card in self.hand)
But it might be even better to create a Hand class that wraps up a list of cards, and pass that around, instead of using a list directly.
You are not running the functionality you want because you are referencing player.hand. Try changing
str(self.player.hand)
to
str(self.player)

Categories

Resources