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)
Related
I am creating an Among Us ripoff (for fun!) and the while True & if/elif/else statements will only return false (not An Impostor) with the inputs. I had created a list for the names and 2 random elements from the list will be chosen as An Impostor. However, whenever I input a name that is The Impostor, it will only return
(player) was not An Impostor.
Here is my code;
import sys, time, random
names = ["player1", "player2", "player3", "player4", "player5", "player6", "player7", "player8", "player9", "player10"]
print("Players: ")
for x in names:
print(x)
print('—————————————————————————')
impostor1 = random.choice(names)
impostor2 = random.choice(names)
crewmates = 8
impostors = 2
tries = 6
while True:
talk = input("Guess who The Impostor(s) are. " + str(crewmates) + " Crewmates are left. " + str(impostors) + " Impostors are left. You have " + str(tries) + " tries left.")
if talk in names:
print(talk + " was voted for.")
time.sleep(0.1)
if talk != impostor1 or talk != impostor2:
notimp = talk + " was not An Impostor. "
names.remove(talk)
for y in notimp:
sys.stdout.write(y)
sys.stdout.flush()
time.sleep(0.05)
crewmates -= 1
tries -= 1
elif talk == impostor1 or talk == impostor2:
wasimp = talk + " was An Impostor. "
names.remove(talk)
for v in wasimp:
sys.stdout.write(v)
sys.stdout.flush()
time.sleep(0.1)
impostors -= 1
else:
print("That player was either ejected or is not a valid player.")
However, whenever I put the Impostor in the input, it says it isn't An Impostor?
I think this line is the source of the problem:
if talk != impostor1 or talk != impostor2:
Let's say impostor1 is player1 and impostor2 is player2 and someone input in player1, according to Python Boolean expression operator or that if statement will evaluate like this:
if player1 != impostor1 evaluated to False because player1 is indeed equals to impostor1.
So far so good, but because the first test is a False, Python simply evaluates and returns the right side operand which may be either True or False. In your case Python will evaluate if talk != impostor2 and return True, thereafter executes the nested block.
I was wondering if there was a way to input 2 items into an array (2 dimensional) at least. One part of the array to hold the name of the person that was golfing, and the other part of the array to hold the score of the person that was playing.
scores = []
playerName = "Cynthia"
playerScore = "72"
scoreEntry = [playerName, playerScore]
The code above shows it being hard coded into it so the resulting would be [Cynthia, 72], but I am trying to figure out how to grab the input from the user and tried applying directly to the array, but it ends up coming out to this below.
How many players: 1
Enter a name: Cynthia
Enter a score: 72
Data written out is: C : y
Data written out is: 7 : 2
This is the output im currently getting
Code below for what I used to get this
def main():
golfFile = open ("golf.dat", 'w')
scores = []
SIZE = getSize()
playerName = getName(scores, SIZE)
playerScore = getScore(scores, SIZE)
scoreEntry = [playerName, playerScore]
scores.append(scoreEntry)
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
golfFile.close()
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName(scores, SIZE):
index = 0
while (index <= SIZE - 1):
nameInput = input("Enter a name: ")
scores.append(nameInput)
index = index + 1
return scores
def getScore(scores, SIZE):
index = 0
while(index <= SIZE - 1):
scoreInput = input("Enter a score: ")
scores.append(scoreInput)
index = index + 1
return scores
main()
Expected output is
[Cynthia, 72]
There is an error that comes up as well
Traceback (most recent call last):
File "d:\Programs\test.py", line 35, in <module>
main()
File "d:\Programs\test.py", line 11, in main
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
TypeError: can only concatenate list (not "str") to list
Also, I do not want to use any libraries at all for this
You're appending to scores in the getName() and getScore() functions, and each of them return the whole scores list. Then you're putting those two references to scores in the scoreEntry list, and then appending that list to scores again. So you've got the lists nested several levels deep, and you never have each name in the same list as the corresponding score.
Instead, you should just read one name and score each time through a single loop. Put those in a scoreEntry tuple, and append that to the scores list.
def main():
scores = []
SIZE = getSize()
for _ in range(SIZE):
playerName = getName()
playerScore = getScore()
scoreEntry = (playerName, playerScore)
scores.append(scoreEntry)
with open ("golf.dat", 'w') as golfFile:
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName():
nameInput = input("Enter a name: ")
return nameInput
def getScore():
scoreInput = int(input("Enter a score: "))
return scoreInput
main()
I am having an issue with calling variables to add while within a definition which is in the class 'mountain'. It runs the error:
AttributeError: 'function' object has no attribute 'picture'
Here is the code for it:
import random
class currencies:
film = 5
class pictures:
picture = {"m_goat": 0, "b_eagle": 0, "marmot": 0, "r_snake": 0, "m_lion": 0, "b_dragon": 0, "vulture": 0}
class location:
city = True
shop = False
mountains = False
desert = False
class mountain:
#Travel to mountains
def travel_m():
print("You climb to the top of a tall mountain")
location.mountains = True
animals = ["mountain goat", "bald eagle", "marmot", "rattlesnake", "mountain lion"]
animal_pics = ["m_goat", "b_eagle", "marmot", "r_snake", "m_lion"]
if 1 == 1: #for simplicity I changed this to a non random number
animal = random.randint(0, 4)
str_animal = animals[animal]
ans = input("You see a wild " + str_animal + ". Would you like to take a photo? (y/n) \n")
if ans == "y" and currencies.film == 0:
print("You cannot take a picture of this animal because you are out of film")
elif ans == "y":
currencies.film -= 1
pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1 #this is the line with the error
print("You took a picture of the animal")
elif ans == "n":
print("The animal was left unbothered")
else:
print("I do not recognize that command")
def pictures():
print("You have " + str(pictures.pictures['m_goat']) + " picture(s) of mountain goats")
print("You have " + str(pictures.pictures['b_eagle']) + " picture(s) of bald eagles")
print("You have " + str(pictures.pictures['marmot']) + " picture(s) of marmots")
print("You have " + str(pictures.pictures['r_snake']) + " picture(s) of rattlesnakes")
print("You have " + str(pictures.pictures['m_lion']) + " picture(s) of mountain lions")
mountain.travel_m()
Thank you for any help at all. I'm just learning the language but neither me nor my teacher could find an answer for it online. If it's something stupid, please do say
When you do:
def pictures():
you're redefining the variable pictures. It now names the function, not the class that was defined earlier.
Give the function a name that doesn't conflict with the class, e.g.
def show_pictures():
Also, in the last function you use pictures.pictures. That should be pictures.picture.
After you fix those, this line is wrong:
pictures.picture[animal_pics] = pictures.picture[animal_pics] + 1
animal_pics is a list, you can't use it as a dictionary key. I think you meant:
pictures.picture[str_animal] += 1
I'm trying to get this problem fixed. I'm creating a program which stores the score in a spreadsheet but when it does, it does not write the score and name in different cell. I have tried adding the column string/row string but always getting error, some guide and help will be appreciated.
So far this is what I have done:
!(http://postimg.org/image/6zn9l43bj/)!
I tried to get a heading saying name and the users name below in each cell and same with score and need some starting point/help
ClassA = open('classa.csv', 'w')
ClassB = open('classb.csv', 'w')
ClassC = open('classc.csv', 'w')
start = True
while start:
user =(input("What is your name?"))
form =(input("Which Group are you in A/B or C ")).lower()
import re
import random
from random import randint
score = 0
for i in range(3):
first_num = random.randint(1,10)
second_num = random.randint(1,10)
choice = (first_num+second_num)
if choice == first_num+second_num:
print ("Question (%d)" % (i+1))
print (first_num)
print("Add (+)")
print(second_num)
check = True
while check:
answer = (input('enter the answer: '))
if not (re.match('-?[0-9]\d*(\.\d+)?$', answer)):
print("Only input numbers")
else:
check = False
answer = int(answer)
if answer == (choice):
print("It's correct!")
score +=1
else:
print("It's wrong!")
print ("The correct answer is: ", choice)
print('')
print(user)
if form == 'a':
ClassA.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'b':
ClassB.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
elif form == 'c':
ClassC.write("Name: "+str(user) + ' ' + "Score: "+str(score)+"/10" + '\n')
yesorno = input("Restart?, Y or N ").lower()
if yesorno == 'y':
start = True
elif yesorno == 'n':
start = False
ClassA.close()
ClassB.close()
ClassC.close()
Thanks
A bit of background: CSV stands for Comma Separated Values, oddly enough Values are quite often separated by semicolons in CSV files and, in fact, (I think) Excel won't recognise columns if you use commas, but it will if you use semicolons. Edit: As pointed out in the comments, this probably depends on regional settings, if in your country the decimal point is usually a comma (e.g. most of Europe) use ;, if it's usually a point use , as separator.
So, back to your question: you are not separating your values, use this instead (notice the semicolon):
ClassA.write("Name: "+str(user) + '; ' + "Score: "+str(score)+"/10" + '\n')
I wouldn't recommend writing the Name: and Score: prefixes either, I would go with a header row (Name; Score; Max Score) and something like this:
ClassA.write("{0}; {1}; {2}\n".format(user, score, max_score))
See also: str.format
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."