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

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)

Related

Name X is not defined even though it is

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.

Why is the menu of my program stuck in an infinite loop?

I'm creating a program so that a track coach can easily pull up runners times as well as input them.
I'm trying to figure out why when I start my program, it runs the function 'MENU', looping it.
user_input = 0
print('MENU')
print('1 - Add runner data to file')
print('2 - Display runners and their times')
print('3 - Calculate the average run time')
print('4 - Display the fastest time')
print('5 - EXIT')
print()
def MENU():
user_input = int(input('Enter your Menu choice >> '))
return -1
def DATA(f_runner, f_time):
f_runner = str(input('Enter runners name >> '))
f_time = str(input('Enter the runners time in hours >> '))
print('Runners data entered into the file.')
f = open('myFile.txt', 'w')
f.write(str(f_runner))
f.write(str(f_time))
f.close()
return f_runner, f_time
def DISPLAY():
contents = f.readlines()
f = open('myFile.txt')
print(contents)
runners_data = 0
runner = 0
runner_time = 0
average_time = 0
file_runner = ''
file_time = 0.0
contents = ''
program_exit = False
menu_start = 0
while program_exit == False:
menu_start = MENU()
while user_input > 0 and user_input < 6:
if user_input == '1':
DATA(file_runner, file_time)
elif user_input == '2':
Display()
elif user_input == '5':
program_exit = True
You are returning -1 instead of user_input in MENU()
Alongside what Samraj said, I believe it's also because your if statement is comparing if the user input is returned as a string, when you're expecting the user to return an int.
You could just remove it from the bottom and have it run inside menu and just call MENU().
Try this and edit it to what you need
print('MENU')
print('1 - Add runner data to file')
print('2 - Display runners and their times')
print('3 - Calculate the average run time')
print('4 - Display the fastest time')
print('5 - EXIT')
print()
def MENU():
the_input = int(input('Enter your Menu choice >> '))
if the_input == 1:
print("hello")
DATA(file_runner, file_time)
elif the_input == 2:
Display()
elif the_input == 5:
exit()
return the_input
def DATA(f_runner, f_time):
f_runner = str(input('Enter runners name >> '))
f_time = str(input('Enter the runners time in hours >> '))
print('Runners data entered into the file.')
f = open('myFile.txt', 'w')
f.write(str(f_runner))
f.write(str(f_time))
f.close()
return f_runner, f_time
def DISPLAY():
contents = f.readlines()
f = open('myFile.txt')
print(contents)
runners_data = 0
runner = 0
runner_time = 0
average_time = 0
file_runner = ''
file_time = 0.0
contents = ''
program_exit = False
menu_start = 0
MENU()

python function skipping around

My intent is to read a list from a file, pick a random number from that list and remove it, then resave the list. Sometimes the function works fine, sometimes not.
choices=[]
with open("C:\\choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices)==0:
choices=[0,1,2,3,4,5]
num=rdm.randint(0,5)
def chooseline(myList, myNum):
print("before if num= "+str(myNum))
if not myNum in myList:
myNum=rdm.randint(0,5)
chooseline(myList,myNum)
print("In NOT-IF num= "+str(myNum))#<-- Need to move before chooseline to print. ok
else:
myNum=myList.pop(myList.index(myNum))
print("in Else num= "+str(myNum))
print("end num= "+str(myNum))
return myNum
newnum= chooseline(choices,num)
with open("C:\\choices.txt", "w") as f:
for e in choices:
f.write(str(e) +"\n")
As long as the random number is in the list the function returns as expected, but if the first number is not on the list, it seems to loop back.
runfile('...')
before if num= 0
in Else num= 0
end num= 0
runfile('...')
before if num= 2
in Else num= 2
end num= 2
runfile('...')
before if num= 2 #ok not in list
before if num= 0 #ok chooses new number, but not in list
before if num= 4 # chose 4, in list
in Else num= 4 # as expected
end num= 4 #<----- expect to stop here and return 4
In NOT-IF num= 4
end num= 4 #
In NOT-IF num= 0
end num= 0
There is an easier and more efficient approach ...
import random
lines = []
with open('choices.txt', 'r') as file:
for line in file:
lines.append(int(line.rstrip()))
file.close()
with open('choices.txt', 'w') as file:
if len(lines) > 1:
number = lines[random.randint(0, len(lines) - 1)]
for line in lines:
if line != number:
file.write(f'{line}\n')
file.close()
Example without the recursion as mentioned in the comments:
import random
choices = []
with open("choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices) == 0:
choices = [0, 1, 2, 3, 4, 5]
num = random.randint(0, 5)
def choose_num_in_list(max_attempts=100):
chosen_number = -1
attempts = 0
while chosen_number == -1 and attempts < max_attempts:
candiate_number = random.randint(0, 5)
attempts = attempts + 1
if candiate_number in choices:
chosen_number = candiate_number
return chosen_number
newnum = choose_num_in_list()
if(newnum != -1):
choices.pop(choices.index(newnum))
print(f"Removed {str(newnum)} from the list")
else:
print("Failed to remove a number from the list")
with open("choices.txt", "w") as f:
for e in choices:
f.write(str(e) + "\n")

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.

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