python unboundLocalError why - python

import os
def createFile():
if os.path.exists("highscores.txt") == False:
myFile = open("highscores.txt","w")
myFile.close()
def inputInt():
number = input(str("please input your score "))
try:
return int(number)
except:
print ("this is not an acceptable input, please try again")
inputInt()
def addScore():
name = input("Please enter the name you wish to add")
score = inputInt()
messages = "thank you"
'''open the highscores line and read in all the lines to a list called scorelist.
then close the file'''
scoresFile = open("highscores.txt","r")
scoresList = scoresFile.readlines()
scoresFile.close()
#check each line in the scoresList list
for i in range(0,len(scoresList) ):
#check to see if the name is in the line
if name in scoresList[i]:
#if it is then strip the name from the text. this should leave theb score
tempscore = scoresList[i].replace(name,"")
#if the score is higher then add it to the list
if int(tempscore)<score:
message = "Score updated"
scoresList[i] = (name + str(score))
#write the scores back to the file
scoresFile = open("highscores.txt","w")
for line in scoresList:
scoresFile.write(line + "\n")
scoresFile.close()
#no need to continue so break
break
else:
#message as score too low
message= "score too low. not updated"
if message("Score updated"):
message = "New score added"
scoresFile = open("highscores.txt","a")
scoresFile.write(name + str(score) + "\n")
scoresFile.close()
print (message)
addScore()
Above is the code. The error shown is:
Traceback (most recent call last):
File "E:\Computer Science\python code\highScores\highscores1.py", line 66, in <module>
addScore()
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore
File "E:\Computer Science\python code\highScores\highscores1.py", line 60, in addScore
if message("Score updated"):
UnboundLocalError: local variable 'message' referenced before assignment

(1) You are referring to message which is undefined when no names are found in scoresList[i]. Put a
message = ""
line before your for loop. I don't know your actual intent, so this will make the error go away but check if the logic is still correct.
(2) You are doing the comparison incorrectly. You should write
if message == "Score updated":
instead of
if message("Score updated"):

Related

Error prompt instead of prompt to re enter input

I am making a price is right game. I am currently working on a game mode similar to the contestant row, where they guess the price of an item.
When it asks you to submit a bid, if you enter a word (instead of a bid), the program crashes and displays the following error:
"Traceback (most recent call last):
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 36, in
contestantrow()
File "C:\Users\alexe\AppData\Local\Programs\Python\Python36\Thepriceisright.py", line 24, in contestantrow
protagnum=int(input(propername +", what is your bid?"))
ValueError: invalid literal for int() with base 10: 'alexei'"
Here's my code:
import random
print(" The Price is Sorta Right - 000776331")
welcomeplayer = True
contestantrow = True
def welcome():
while True:
global welcomeplayer
global propername
welcomeplayer = input("Please enter your name using only letters")
validname = welcomeplayer.isalpha()
propername = welcomeplayer.capitalize()
if validname == True:
print( propername, " ! Come on down! You're the next contestant on the Price is (sorta) right")
print (" Dew Drop welcomes " ,propername ," to contestants row joining EIMNOT A. HUMAN,ARTHURFICIAL EINTEL , ROBORT")
return
else:
print("Please only write letters on your name tag")
welcomeplayer = False
def contestantrow():
while True:
print("Dew Drop shows the price that you are bidding on")
protagnum=int(input(propername +", what is your bid?"))
if protagnum > 0:
componebid = random.randint(1,1000)
print("EIMNOT A. HUMAN bids: ",componebid)
comptwobid = random.randint(1,1000)
print("ARTHURFICIAL EINTEL bids: ",comptwobid)
compthreebid =random.randint(1,1000)
print("ROBORT bids: ",compthreebid)
else:
print(" Dew Drop says [Im sorry bids should start at atleast one dollar]")
contestantrow = False
welcome()
contestantrow()
protagnum=int(input(propername +", what is your bid?"))
You're converting an int / string to int. "1" will work but "a" will raise a ValueError
while True:
try:
protagnum=int(input(propername +", what is your bid?"))
break
except ValueError:
print("Invalid bid, please try again")

Using str.replace gives me a TypeError: 'str' object cannot be interpreted as an integer

I have a homework about making a phone book. And I did a code.
import sys
print("Type 'help' to learn commands ")
command = ("show_list, add_person, delete_person, search_person, exit")
command1 = ()
list1 = {}
while True:
command1 = input("Command: ")
saved = open("PhoneBook.txt", "a")
if command1 == "help":
print(command)
print()
elif command1 == "show_list":
saved = open("PhoneBook.txt", "r")
print(saved.read())
saved.close()
elif command1 == "add_person":
name = str(input("Name: "))
number = int(input("Number: "))
list1[name] = number
saved = open("PhoneBook.txt", "w")
saved.write("\n-------------")
saved.write(str(name))
saved.write(":")
saved.write(str(number))
saved.write("-------------\n")
saved.close()
elif command1 == "search_person":
search = open("PhoneBook.txt", "r")
search1 = input("Name:")
for line in search:
if search1 in line:
print("\n")
print(search)
elif command1 == "delete_person":
del0 = open("PhoneBook.txt", "r+")
del1 = str(input("Name: "))
for line in del0:
if del1 in line:
del2 = line.replace(" ", " ", " ")
del0.write(silinecek3)
del0.close()
elif command1 == "exit":
sys.exit()`
And everything is good (I think), except deleting a name. Because when I try to delete a name, it gives me an output:
Traceback (most recent call last):
File "C:/Users/oyuni/Desktop/ödeving.py", line 47, in <module>
del2 = line.replace(" ", " ", " ")
TypeError: 'str' object cannot be interpreted as an integer
And I don't know what to do. Can anyone help me to fix the code?
str.replace() can take either 2 or 3 arguments, but that 3rd argument must be an integer (it limits the number of replacements that take place).
You passed in a string as the third argument:
line.replace(" ", " ", " ")
Pass in just two strings, and make those different strings if you actually want to replace anything:
line.replace(" ", "")
However, this won't delete the name. The rest of that block of code is going to give you more problems:
You didn't define the name silinecek3
You can't safely read and write to the same file, at the same time. Read all of the file into memory first, or write to a new file that then is moved back into place.
You want to remove names entirely; do so by writing out all names you keep (so filter out the lines, write each one that doesn't have the name).

How to sort a .txt file numerically

I am having trouble sorting my .txt file by a numerical value. I have attached the code and am trying to get it to sort by score,
I also cant get it to print each new score to a new line from the txt file.
def Highscore():
name = input("What is your name for the scoreboard?")
newhighscore =(name, highscore)
newline = ("\n")
HighscoreWrite = open ("highscore.txt", "a")
HighscoreWrite.write(highscore )
HighscoreWrite.write(name )
HighscoreWrite.write("\n")
HighscoreWrite.close()
HighscoreRead = open("highscore.txt", "r" )
ordered = sorted(HighscoreRead)
print (ordered)
print (HighscoreRead.read())
#print (newhighscore)
HighscoreRead.close()
retry = "Yes"
while retry == "Yes":
print ("Welcome to this quiz.\n")
score = 0
attempt = 0
while score < 10:
correct = Question()
if correct:
score += 1
attempt += 1
print ("Well done, You got it right")
else:
print ("Good try but maybe next time")
attempt += 1
highscore = score, ("/") ,attempt
highscore = str(highscore)
message = print ("You scored", (score), "out of ",(attempt))
Highscore();
retry = input("Would you like to try again? Yes/No")
In order to sort a file numerically, you must create a key(line) function that takes a line as parameter and returns the numeric value of the score.
Assuming that highscore.txt is a text file where each line starts with a numerical value followed with a space, the key function could be:
def key_func(line):
return int(line.lstrip().split(' ')[0])
You can then use ordered = sorted(HighscoreRead, key = key_func)
As it is a one line function, you can also use a lambda:
ordered = sorted(HighscoreRead, key= (lambda line: int(line.lstrip().split(' ')[0])))

Python for absolute beginners chapter 7 challenge 2

I am currently working through the python for absolute beginners 3rd addition. I am struggling with the 2nd challenge in the 7th chapter of the book, as i keep getting an error i don't understand.
The challenge is to:
"improve triva challenge game so that it maintains a high score list in a file. The program should records the player's name and score if the player makes the list. store the high scores using a pickled object."
The original code
# Trivia Challenge
# Trivia game that reads a plain text file
import sys
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
return category, question, answers, correct, explanation
def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("You're final score is", score)
main()
input("\n\nPress the enter key to exit.")
my attempt at the challenge code
# Trivia Challenge
# Trivia game that reads a plain text file
import sys, pickle
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)
points = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
return category, points, question, answers, correct, explanation
def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def high_scores():
global score
value = int(score)
name = input("What is your name? ")
entry = (value, name)
f = open("high_scores.dat", "wb+")
high_scores = pickle.load(f)
high_scores.append(entry)
high_scores = high_scores[:5]
print("High Scores\n")
print("NAME\tSCORE")
for entry in high_scores:
value, name = entry
print(name, "\t", value)
pickle.dump(high_scores, f)
f.close()
def main():
trivia_file = open_file("trivia.txt", "r")
title = next_line(trivia_file)
welcome(title)
# get first block
category, points, question, answers, correct, explanation = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
j = int(points)
global score
score += j
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, points, question, answers, correct, explanation = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("You're final score is", score)
high_scores()
score = 0
main()
input("\n\nPress the enter key to exit.")
And the wonderfully confusing error
Traceback (most recent call last):
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 104, in <module>
main()
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 100, in main
high_scores()
File "C:\Users\Cheyne\Desktop\Python\chapter07\Challenges\temp.py", line 54, in high_scores
high_scores = pickle.load(f)
File "C:\Python31\lib\pickle.py", line 1365, in load
encoding=encoding, errors=errors).load()
EOFError
Can anyone help explain what's going wrong here please? I have been staring at it for days.
You have an "EOFError", which is an "End Of File Error" at line 54.
That's where you try to load the pickle file so, considering that you are not checking that the file actually exists, my guess is that you have no file and get the error.
Either create an initial file by yourself, or check that it exists and is valid before trying to load it.
EDIT: I just noticed that you open the pickle file as "wb+", which means that you open it for writing and try to read it. You're overwriting the file, which becomes zero bytes. If you want to append to the existing file, you should use "a" instead of "w". Again, before loading make sure the file contains valid data.

calling a variable from outside the function using python

I have this script that allow the user to enter the file name by an argument and then it updates the file version:
#!/usr/bin/env python
import os
import sys
class versionBumper:
def __init__(self):
self.version = None
self.SavedBefore = ""
self.SavedAfter = ""
def change_version(self, file_to_be_modded, packageVersion):
for line in file_to_be_modded:
if packageVersion in line:
print "VERSION FOUND: ", line
self.VersionNumber = line
elif self.VersionNumber is None:
self.SavedBefore += line
else:
self.SavedAfter += line
file_to_be_modded.close()
print "Version: ", self.VersionNumber
return self.VersionNumber
if __name__ == '__main__':
print "sys.argv[1:]:", sys.argv[0:]
versionBumper123 = versionBumper()
filename = sys.argv[1]
path = "/home/Desktop/Crate/Crate/" + filename + "/build/CMakeLists.txt"
if os.path.exists:
inputFile = open(path, 'r')
else:
print "no match found"
sys.exit()
print "Which version number to bump ?"
print "1) major"
print "2) minor."
print "3) patch."
Choose_version = raw_input("Choose version: ")
if Choose_version == "1":
version = versionBumper123.change_version(inputFile, "_MAJOR ")
elif Choose_version == "2":
version = versionBumper123.change_version(inputFile, "_MINOR ")
elif Choose_version == "3":
version = versionBumper123.change_version(inputFile, "_PATCH ")
else:
print "Invalid input. Exiting gracefully..."
sys.exit()
outputFile = open (path, 'w')
splitted_version_line_substrings = version.split('"')
Version_Name = splitted_version_line_substrings[0]
Version_Number = int(splitted_version_line_substrings[1]) + 1
parenthesis = splitted_version_line_substrings[2]
new_version = (str(Version_Name) + '"'
+ str(Version_Number) + '"'
+ str(parenthesis))
print "new_version: ", new_version
outputFile.write(str(versionBumper123.SavedBefore))
outputFile.write(str(new_version))
outputFile.write(str(versionBumper123.SavedAfter))
But I keep getting this error:
Traceback (most recent call last):
File "untitled.py", line 57, in <module>
splitted_version_line_substrings = version.split('"')
NameError: name 'version' is not defined.
I also tried to define version as a global variable but that also did not work, I can't really figure out how to call version from outside the function it is defined in.
Me thinks that you are dealing with a single instance of your class versionBumper
versionBumper123 = versionBumper()
so I guess that what you want to do with the statement
splitted_version_line_substrings = version.split('"')
should be expressed as
splitted_version_line_substrings = versionBumper123.version.split('"')
Just because you use a single instance of your class, imho you could write simpler code if you don't use a class.

Categories