Name X is not defined even though it is - python

Here is the code:
from colorama import *
import os
os.system('color FF')
print(Fore.GREEN+' {:<20} '.format('['+ Fore.RED+'1'+Fore.GREEN+'] Πρωινά'),
Fore.GREEN+' {:^20} '.format('['+ Fore.RED+'2'+Fore.GREEN+'] Μεσημεριανά'),
Fore.GREEN+' {:>20} '.format('['+ Fore.RED+'3'+Fore.GREEN+'] Βραδινά'))
y = input()
# Πρωινά
if y == '1':
print("Ακόμα τίποτα")
x = input()
# Μεσιμεριανά
if y == '2':
print(Fore.GREEN + ' {:<20} '.format('['+ Fore.RED+'1'+Fore.GREEN+'] Μπριζόλες στον φούρνο'),
Fore.GREEN+' {:^20} '.format('['+ Fore.RED+'2'+Fore.GREEN+'] Πατάτες στον φούρνο'))
z = input()
# Βραδινά
if y == '3':
print("Ακόμα τίποτα")
c = input()
# Πρωινά
if x == '1':
f = open("mpriz_fourno.txt", "r")
file_contents = f.read()
print(file_contents)
f.close()
if x == '2':
f = open("asd.txt", "r", encoding="utf8")
file_contents = f.read()
print(file_contents)
f.close()
if x == '3':
f = open("patates.txt", "r")
file_contents = f.read()
print(file_contents)
f.close()
# Μεσιμεριανά
if z == '1':
f = open("patates_fourno.txt", "r", encoding="utf8")
file_contents = f.read()
print(file_contents)
f.close()
# Βραδινά
if c == '1':
print("test")
input(Fore.RED + "\nPress Enter to exit")
So basically, some parts of the code are in Greek so I guess you will not be able to understand everything. I am making a virtual food recipe book but when I try to run it I get the following error at some point:
line 29, in <module>
if x == '1':
NameError: name 'x' is not defined
What should I do?

The issue stems from x only being defined if either y == '1' or y == '2'.
There are a number of ways to fix this problem, depending on how the program should work.
For instance, you could initialize the variables to a default value.
x = ""
z = ""
c = ""
This way, they can be accessed without causing a crash, as they are defined in the namespace.
Alternatively, you might change the control flow of your program by chaining or nesting the if-statements. Ensuring that x is only accessed after initialization.
By using an else-clause, and giving x a value in each of the branches, x will always end up with a value. Regardless of which if-statement ends up being true.
y = input()
if y == '1':
x = input()
elif y == '2':
x = ""
...
elif y == '3':
x = ""
else:
x = ""
...
Structure with nesting if-statements:
if y == '1':
x = input()
if x == '1':
...
elif x == '2':
...
elif x == '3':
...
else:
print("X needs to be 1, 2 or 3")

In the question code, x was only defined inside the if y == '1': statement.
Unlike some other languages, x is actually undefined (ie. it does not even take the value None) until it becomes defined.
So when y is not equal to 1 the code containing x=input() is never executed. So x does not exist in the code as far as python is concerned since that line is never executed.
This is the actual corrected code with comments so that you can see the obvious error.
from colorama import *
import os
os.system('color FF')
print(Fore.GREEN+' {:<20} '.format('['+ Fore.RED+'1'+Fore.GREEN+'] Πρωινά'),
Fore.GREEN+' {:^20} '.format('['+ Fore.RED+'2'+Fore.GREEN+'] Μεσημεριανά'),
Fore.GREEN+' {:>20} '.format('['+ Fore.RED+'3'+Fore.GREEN+'] Βραδινά'))
x = 100 # <---- add something here so that x is defined
y = input()
# Πρωινά
if y == '1':
print("Ακόμα τίποτα")
x = input() # if y is not equal to 1 then x is never defined
# Μεσιμεριανά
if y == '2':
print(Fore.GREEN + ' {:<20} '.format('['+ Fore.RED+'1'+Fore.GREEN+'] Μπριζόλες στον φούρνο'),
Fore.GREEN+' {:^20} '.format('['+ Fore.RED+'2'+Fore.GREEN+'] Πατάτες στον φούρνο'))
z = input()
# Βραδινά
if y == '3':
print("Ακόμα τίποτα")
c = input()
# Πρωινά
if x == '1':
f = open("mpriz_fourno.txt", "r")
file_contents = f.read()
print(file_contents)
f.close()
if x == '2':
f = open("asd.txt", "r", encoding="utf8")
file_contents = f.read()
print(file_contents)
f.close()
if x == '3':
f = open("patates.txt", "r")
file_contents = f.read()
print(file_contents)
f.close()
# Μεσιμεριανά
if z == '1':
f = open("patates_fourno.txt", "r", encoding="utf8")
file_contents = f.read()
print(file_contents)
f.close()
# Βραδινά
if c == '1':
print("test")
input(Fore.RED + "\nPress Enter to exit")
And here is a very simple snippet that highlights the error:
y = 99
# x is undefined
if y == 10:
x = 'hello world' # this line is never run since 99 != 10
# x is still not defined because the line above was never executed
# this print statement will fail because 'name 'x' is not defined'
print(x)
I hope that explanation is helpful along with the other useful comments.

Related

Is there a command for exiting and re-entering a script?

Sorry for the other post, it had an error.
My simplified code:
#test
import json
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
and
#test2
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)
I have two codes so I don't overwrite the numbers of test2 with test
This is already kinda what I want, but my output for n = 4 and n = 5 is:
1
Number: 4
5
Number: 5
10
Number:
And so on...
But instead, I want the code to Exit completely and then start it again without me doing it manually. Kinda like:
1
Number: 4
Code restarts
5
Number: 5
Code restarts
5
Number: 10
and so on. Thank you :-)
If I understood you correctly , You will have to create two separate scripts
test1.py
#test
import json
import os
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
os.system('python test2.py') # this line will run the second script
test2.py
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)

Python file appears to be empty after a function

Code:
import os, csv
def menu():
print("Welcome to da sporty ting" + "\n" + "Menu options: " + "\n")
print("1 - Run the code")
print("2 - Exit")
menu_choice = int(input("Enter choice: "))
while menu_choice not in (1, 2):
menu_choice = int(input("Error, try again: "))
if menu_choice == 1:
finding_file()
elif menu_choice == 2:
exit()
def finding_file():
print("\n")
print("Text file options" + "\n")
print("1 - testfile 1" + "\n" + "2 - testfile 2" + "\n" + "3 - Other")
txt_menu_option = int(input("Enter choice: "))
print("\n")
while txt_menu_option not in (1, 2, 3):
txt_menu_option = input(input("Error, try again: "))
if txt_menu_option == 1:
filename = "Test1_Votes.txt"
pass
elif txt_menu_option == 2:
filename = "Test2_Votes.txt"
pass
elif txt_menu_option == 3:
filename = str(input("Enter name of txt file (don't include .txt at he end) : "))
filename = filename + ".txt"
file_exists = os.path.exists(filename)
if file_exists == False:
print("File does not exist, returning to menu")
menu()
pass
file_validity(filename)
def file_validity(filename):
f = open(filename, 'r+') # opening file in read/write mode
inv_lines_cnt = 0
valid_list = [0, 0, 1, 2, 3] # sorted list of valid values
lines = f.read().splitlines()
f.seek(0)
f.truncate(0) # truncating the initial file
for l in lines:
if sorted(map(int, l.split(','))) == valid_list:
f.write(l + '\n')
else:
print(l + " is a invalid line")
inv_lines_cnt += 1
print("There were {} invalid line/lines.".format(inv_lines_cnt))
calculate_quota(filename)
def calculate_quota(filename):
f = open(filename, 'r+')
lines = f.readlines()
print("Calculate quota " + str(lines))
seats = 2
line_count = 0
for line in lines:
line_count += 1
quota = 0
quota == int((line_count / (seats + 1)) + 1)
print(quota)
quota_required(quota, lines)
def quota_required(quota, lines):
for line in lines:
lines.rstrip(',')
lines.rstrip('\n')
print(lines)
candidate_fp_votes = [0,0,0,0,0]
for line in lines:
for i in range(5):
if line[i] == 1:
print ("if working")
candidate_fp_votes[i] += 1
print (candidate_fp_votes)
print (candidate_fp_votes)
Text file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
0,1,2,3,0
Currently I have a problem where after file_validity(), the text file just appears to have loaded up as empty as when I re-open the file in the next function, it prints lines as empty. file_validity() just deletes the file, and rewrites the valid votes. As you can see I have tried to find out where the trouble lies. I believe the truncate and seek functions seem to be causing some trouble but I am not sure if this is true. And if it were to be the case, how to fix it.
Any help?
Thanks in advance.

'list' object is not callable, not a rename issue

as the title say i have been searching the solution of this problem :
TypeError: 'list' object is not callable
for a while, but i did find only answers about naming variables with defaults names like, for instance, list. And i think this is not my case, in particular this the concerned code:
next_matrix = 0
c = 0
routes = []
mapp_matrix = []
mapp = []
def del_nl(l):
for i in range(len(l)):
del l[i][-1]
# check if there is a valid route in a map from a starting point
def route(n_map, n_command, s_point):
for i in n_command:
if i == 'N':
s_point[0] = s_point[0] - 1
elif i == 'S':
s_point[0] = s_point[0] + 1
elif i == 'E':
s_point[1] = s_point[1] + 1
elif i == 'W':
s_point[1] = s_point[1] -1
try:
if n_map[s_point[0]][s_point[1]] != '.':
return False
except IndexError:
return False
return True
## Getting datas for every map ##
with open("/home/senso/programming/ctf_magio/input-sample.txt", "r") as f:
for line in f:
# i am reading values for the dimension of the map
if c == next_matrix:
line = line.split(" ")
int_list = [int(i) for i in line]
if not c == 0:
del_nl(mapp)
mapp_matrix.append(mapp[:])
del mapp[:]
# reading the commands
elif c == next_matrix + 1:
route = list(line)
del route[-1]
routes.append(route)
next_matrix = next_matrix + int_list[0] + 2
else:
#building the map
mapp.append(list(line))
c = c+1
del_nl(mapp)
mapp_matrix.append(mapp[:])
ship_alive = 0
for i in range(len(mapp_matrix)):
for j in range(len(mapp_matrix[i])):
for z in range(len(mapp_matrix[i][j])):
#oh my god is O(n^3), will it explode??
if mapp_matrix[i][j][z] == '.':
point = [j, z]
if route(mapp_matrix[i], routes[i], point):
ship_alive = 1 + ship_alive
and i get this error
File "capitanSonar.py", line 78, in
if route(mapp_matrix[i], routes[i], point):
TypeError: 'list' object is not callable
If i try to call 'route' with static lists it works.
Any help is appreciated.
# reading the commands
elif c == next_matrix + 1:
route = list(line) # <- Here. Pick a different name for the list
del route[-1]
routes.append(route)
next_matrix = next_matrix + int_list[0] + 2
else:
#building the map
mapp.append(list(line))
c = c+1

Python - print value to new file?

import sys
import pickle
import string
def Menu():
print ("\n***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def Loop():
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
user_File = ReadTextFile()
elif choice == 2:
DisplayCounts(user_File)
elif choice == 3:
DisplayStats(user_File)
elif choice == 4:
PrintStats(aDictionary)
else:
print ("Error.")
def ReadTextFile():
print "\n"
while True:
InputFile = input("Please enter a file name (NOTE: must have quotation marks around name and extension): ")
if (InputFile.lower().endswith('.txt')):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return InputFile
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def DisplayStats(InputFile):
print "\n"
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(InputFile, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def PrintStats(aDictionary):
print "\n"
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
Loop()
There's something with that last function that is really tripping me up. I keep getting errors. I know aDictionary is not defined but I do not even know what to define it as! Any of you guys have an idea? Thanks.
with open("some_file.txt","W") as f:
print >> f, "Something goes here!"
its hard to say without your errors. .. but you almost certainly need to have aDictionary defined
also probably something like
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
return dict(numbers=numCount,
comma=commaCount,
dot=dotCount,
line=lineCount,
word=wordCount)
result = DisplayCounts("someinput.txt")
print result

Trying to write a string to a tempfile

I'm making a game of 20 questions. In the code I've created a tempfile to keep track of the user's questions. Here's the code:
import random
import turtle
import tempfile
import gzip
def getAnswer():
obj = random.randrange(5)
if obj == 0:
infile1 = open("appleyes.txt", "r")
infile2 = open("applecanbe.txt", "r")
answer = "apple"
elif obj == 1:
infile1 = open("dogyes.txt", "r")
infile2 = open("dogcanbe.txt", "r")
answer = "dog"
elif obj == 2:
infile1 = open("carrotyes.txt", "r")
infile2 = open("carrotcanbe.txt", "r")
answer = "carrot"
elif obj == 3:
infile1 = open("flyyes.txt", "r")
infile2 = open("flycanbe.txt", "r")
answer = "fly"
elif obj == 4:
infile1 = open("caryes.txt", "r")
infile2 = open("carcanbe.txt", "r")
answer = "car"
print(answer)
return infile1, infile2, answer
def startAsking(infile1, infile2):
count = 1
tfile = tempfile.TemporaryFile()
while count <= 20:
ask = input("Is it/Does it have: ")
if ask.isalpha():
if ask.lower() in tfile:
print("You've already asked this.\n")
else:
with gzip.open(tfile+".gz","wb") as f_out:
f_out.write(bytes(ask, 'UTF-8'))
if ask.lower() in infile1.split():
print("Yes it is/Yes it could\n")
count = count + 1
elif ask.lower() in infile2.split():
print("It can be/It could\n")
count = count + 1
else:
print("No or not sure\n")
count = count + 1
else:
print("No numbers or symbols please.\n")
infile1.close()
infile2.close()
tfile.close()
def guessingTime(answer):
print("That's 20! Time to guess.\n")
guess = eval(input("Is it a(n): "))
if guess.lower() == answer:
print("You got it! Congratulations!\n")
else:
print("Sorry, but the answer was\n")
def main():
infile1, infile2, answer = getAnswer()
startAsking(infile1, infile2)
guessingTime(answer)
main() `#Brian Reser H787A975
#Python Project
#Program plays 20 questions with the user. It randomly pulls a text file for the answer and keeps track of the user's answers.
import random
import turtle
import tempfile
import gzip
def getAnswer():
obj = random.randrange(5)
if obj == 0:
infile1 = open("appleyes.txt", "r")
infile2 = open("applecanbe.txt", "r")
answer = "apple"
elif obj == 1:
infile1 = open("dogyes.txt", "r")
infile2 = open("dogcanbe.txt", "r")
answer = "dog"
elif obj == 2:
infile1 = open("carrotyes.txt", "r")
infile2 = open("carrotcanbe.txt", "r")
answer = "carrot"
elif obj == 3:
infile1 = open("flyyes.txt", "r")
infile2 = open("flycanbe.txt", "r")
answer = "fly"
elif obj == 4:
infile1 = open("caryes.txt", "r")
infile2 = open("carcanbe.txt", "r")
answer = "car"
print(answer)
return infile1, infile2, answer
def startAsking(infile1, infile2):
count = 1
tfile = tempfile.TemporaryFile()
while count <= 20:
ask = input("Is it/Does it have: ")
if ask.isalpha():
if ask.lower() in tfile:
print("You've already asked this.\n")
else:
with gzip.open(tfile+".gz","wb") as f_out:
f_out.write(bytes(ask, 'UTF-8'))
if ask.lower() in infile1.split():
print("Yes it is/Yes it could\n")
count = count + 1
elif ask.lower() in infile2.split():
print("It can be/It could\n")
count = count + 1
else:
print("No or not sure\n")
count = count + 1
else:
print("No numbers or symbols please.\n")
infile1.close()
infile2.close()
tfile.close()
def guessingTime(answer):
print("That's 20! Time to guess.\n")
guess = eval(input("Is it a(n): "))
if guess.lower() == answer:
print("You got it! Congratulations!\n")
else:
print("Sorry, but the answer was\n")
def main():
infile1, infile2, answer = getAnswer()
startAsking(infile1, infile2)
guessingTime(answer)
main()
The error comes along when it reaches the part where it writes the string "ask" to the tempfile. How do I fix this?
TypeError: unsupported operand type(s) for +: '_TemporaryFileWrapper' and 'str'
The problem is that tfile is a file object and not a string. Fix it by doing something like this:
filename = tfile.name
fullfilename = filename + ".gz"
gzip.open(fullfilename,"wb")
See http://docs.python.org/2/library/tempfile.html for details.

Categories

Resources