I am creating a simple document writer system in python that runs in the IDLE. This is the source code:
def openn():
global n
if n==1:
print("[1] - " + title)
print("[2] - Exit")
option=raw_input()
if int(option)==1:
print(text)
print("type 'done' when done")
do=raw_input()
if do=='done':
run()
if do!='done':
run()
if n==0:
print("No Saved Documents")
def new():
print("Enter a title:")
global title
title=raw_input()
print(str(title) + ":")
global text
text=raw_input()
print("[1] - Save")
print("[2] - Trash")
global n
global save
save=input()
if save==1:
n=1
run()
if save==2:
n=0
run()
def run():
print("[1] - Open a saved document")
print("[2] - Create a new saved document")
global save
save=1
global choice
choice = input()
if choice==1:
openn()
if choice==2:
new()
run()
When I run the program in IDLE for the first time and give the input 1 suggesting I want the program to return "No Saved Documents" it returns the following error:
File "/Users/tylerrutherford/Documents/Python Programs/Operating Systen Project/document_writer.py", line 5, in openn
if n==1:
NameError: global name 'n' is not defined
How can I fix this error?
Thanks in advance!
From looking at your code, you never initialized the variable n in the first place.
You need to define n first.
global n
n = 1
I think it would be a better practice to define the variable outside the function, and then reference it with global inside the function.
n = 1
def open():
global n
Credit to #dshort:
You can pass n in the function to avoid global variables declaration.
Related
The program first asks the user if they'd like to load their own file or use the the file provided by the script.
filename=0
def first(filename):
print('Please Select:')
print('Run Program Now? Press "1"')
start = int(input('Load Your Own List and Run Program? Press "2": '))
if start ==1:
global filename
filename = 'file.txt'
elif start ==2:
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
global filename
filename = tkinter.filedialog.askopenfilename()
else:
print("You didn't enter a valid selection!")
first(filename)
main()
I'm using another function which should call the correct file based on the user input.
def guess(real):
WORDLIST = filename
with open(WORDLIST, 'r') as in_file:
Error:
ErrorSyntaxError: name 'filename' is assigned to before global declaration
This all worked earlier when I had the user input and elif statements within
def guess(real):
Although I wanted to call it separately and that's why I have the user input in it's own function.
You don't need to use return with global variables, however I would avoid using global variables if possible. You might want to read "why are global variables evil" for more details.
A simplified version of the code you provided is shown below using return and then passing the result to another function to avoid using global variables:
def first():
while True:
print('Please Select:')
print('Run Program Now? Press "1"')
start = int(input('Load Your Own List and Run Program? Press "2": '))
if start == 1:
filename = 'file.txt'
return filename
elif start == 2:
filename = 'hello.txt'
return filename
else:
print("You didn't enter a valid selection!")
def second(filename):
print (filename)
filename = first()
second(filename)
I don't understand how I am getting this error, can someone help:
import time
import os
import xlwt
from datetime import datetime
num = 0
def default():
global num
global model
global partnum
global serialnum
global countryorigin
time.sleep(1)
print ("Model: ")
model = input()
print ()
print ("Part number: ")
partnum = input()
print()
print ("Serial Number: ")
serialnum = input()
print ()
print ("Country of origin: ")
countryorigin = input()
print ("Thanks")
num = num+1
xlwt()
def xlwt():
print ("Do you want to write to excel?")
excel = input()
if excel == "y" or "yes":
excel()
else:
print ("Bye")
sys.exit()
def excel():
print ("Enter a spreadsheet name")
name = input()
wb = xlwt.Workbook()
ws = wb.add_sheet(name)
ws.write(0,0,"Model")
ws.write(0,1,"Part Number")
ws.write(0,2,"Serial Number")
ws.write(0,3,"Country Of Origin")
ws.write(num,0,model)
ws.write(num,1,partnum)
ws.write(num,2,serialnum)
ws.write(num,3,countryorigin)
ws.save(name)
def custom():
print()
def main():
print ("Welcome")
print ()
print ("The deafult catagories are: Model, Part Number, Serial Number,"
"country of origin")
time.sleep(1)
print()
dorc()
def dorc():
print ("Would you like to use the default or custom?")
dorc = input ()
if dorc == "default":
default()
elif dorc == "custom":
custom()
else:
print ("Invalid input")
dorc()
main()
When I execute this, I get an error str object is not callable.
You have both a function named excel() and a local variable named excel that you assigned a string to.
You can't do that and expect the function to still be available. The local name excel masks the global, so excel() tries to call the string result that input() returned.
Rename your variable:
print ("Do you want to write to excel?")
choice = input()
if choice in ("y", "yes"):
excel()
Note that I also corrected your variable test; excel == "y" or "yes" does not do what you think it does, programming language logic is not quite the same as English grammar rules. See Why does `a == b or c or d` always evaluate to True?
Next, you make the same mistake by using the name xlwt for both a module you import and a function:
import xlwt
# ...
def xlwt():
# ...
Both the module and the function are global names, and the name can only point to either the module you imported or the function you created, not both at the same time. Rename your function to something else, otherwise the following line will fail too:
wb = xlwt.Workbook()
because xlwt is bound to your function as that was defined later than the module import.
This is the code i have so far for my gcse computing controlled assesment. I a trying to get the user to answer a question, then python will pick out specific words(that are the same as the words stored in a file) then link it to a solution.
global line
global userinput
global word
def main():
global userinput
name=input("What is your name")
print("Hello " +name+ " and welcome to our troubleshooting system!")
userinput=input("What is the problem with your mobile device?")
userinput=userinput.split()
if userinput=="":
print("Please try again")
power_problems()
def power_problems():
global word
global line
global userinput
with open("keywords_1","r+") as datafile_1:
datafile_1.read()
for line in datafile_1:
if "userinput" in line:
print("Hold the restart button for 30 seconds")
else:
phone_problems()
def phone_problems():
global word
global line
global userinput
with open("keywords_2", "r+") as datafile_2:
datafile_2.read()
for line in datafile_2:
if "userinput" in line:
print("Take the phone to the manufacturer to get a replacement")
if __name__ == '__main__':
main()
My problem is that the code stops running after the for loop used in the function "power_problems" and i don't know why
Check your indentation at datafile_1.read() and datafile_1.read()
with open("keywords_1","r+") as datafile_1 - you typed the filename with no file type so the function will stop because there no such file or directory to read.
Try not to use global variables, it just not safe.
Currently my code has a main menu, it asks the user to choose from the option it prints out, this is inside a 'def' function. At the end of the variable I define, there is a input prompt to ask the user for their input named 'option'. However when i run the code i get a syntax. i.e:
The code:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
option = input ("\nEnter your Option: ")
main_menu()
option_class = input("\nWhich Class do you wish to preview: ")
one = "1.txt"
if option == "alpha".lower():
if option_class == "1":
with open (one, "r") as r:
for line in sorted(r):
print (line, end='')
when running the code I receive the following syntax:
NameError: name 'option' is not defined
option is locally defined. You can return entered value from function and assign it to option like this:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
return input ("\nEnter your Option: ")
option = main_menu()
Your variable option is only defined locally in your function main_menu(), not globally.
The variable option is only local to the function main_menu. You can fix it by making option global:
def main_menu():
global option
#...
option = '...'
See: Global vs local variables
I am trying to make a program that can add/delete/show students in a class, and the 5 classes are 5 lists in a list.
Help is greatly appreciated.
When I run this code:
global classes
def intro():
print("Welcome to Powerschool v2.0!")
print("Actions:")
print("1. Add Student")
print("2. Delete Student")
print("3. Show Students in a Class")
print("4. Show All Students")
x = int(input())
while x<1 or x>4:
print ("Please choose an action, 1-4.")
x = int(input())
if x == 1:
action1()
elif x == 2:
action2()
elif x == 3:
action3()
elif x == 4:
action4()
classes = [[],[],[],[],[]]
return classes
def action1():
print("Which Class? 1-5")
a = int(input())
print("Please enter the student's name.")
z = input()
classes[a-1].append(z)
again()
def action2():
print ("Which Class? 1-5")
print ("Which student?")
again()
def action3():
print ("Which Class? 1-5")
y = int(input())
if y == 1:
print (classes[0])
elif y == 2:
print (classes[1])
elif y == 3:
print (classes[2])
elif y == 4:
print (classes[3])
elif y == 5:
print (classes[4])
again()
def action4():
print (classes)
again()
def again():
print("Would you like to do something else? y/n")
h = input()
if h == "y":
intro()
else:
quit
def main():
intro()
main()
My error is:
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 67, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 65, in main
intro()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 19, in intro
action1()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 33, in action1
classes[a-1].append(z)
NameError: name 'classes' is not defined
I did return classes at the end of intro() but I see that doesn't work.
I followed some suggestions, and nothing really happened :/
You're defining classes in your intro method, and, even though it's returning it, your action1 method doesn't see any variable named classes anywhere.
Relevant answer on Python scope and relevant documentation.
return doesn't do what you think it does. return statements are a way of passing execution control back up a context (For example, from intro() to main()), with the ability to send back some information for the higher context to use. Although you're passing classes back to main(), you never do anything with it at that context so it goes away.
One way to solve the problem would be to declare classes as a global variable. This is the easiest thing to do, but isn't generally good design. You could do this either by using the global keyword before declaring the local variable classes in intro() (See this question for guidance on global), or by declaring classes outside any of your functions.
Another solution would be to pass classes as a parameter to your action functions.
In either case, you would need to declare classes before any calls to your action functions.
This is because classes is out of scope for the second two methods. Therefore, you have two options:
Option 1
Pass classes to the methods action1(), action2(), etc like so:
def action1(classes)
...and the when you call it:
action1(classes) //with the classes var you just made
Option 2 (recommended)
Simply put the classes var outside your methods or declare it global like so:
global classes = [[],[],[],[],[]]
...right before:
def intro()
In general, you should read up on how return works; it is not necessary in the code you wrote
classes only exists in intro():, you would have to declare it as a global variable to access it in other functions or declare it outside the function.
classes = [[],[],[],[],[]] # can be accessed by action3() ,action4()
def intro():