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)
Related
I am very new to sw coding needing some help. Thank You!
I have a script that scan a path for .py files and display it it in menu format using enumerates
Ask user to select file/files they want to run and put them in a list
And start ran those file from this list one by one
My issue is that it only ran the the fist selected file from the user selected list. Here is my simple code.
import os
import sys
choice_1 = ''
run_list = []
while choice_1 != 'q':
print("\nPlease select desire test case: ")
items = os.listdir("C:/Users/tonp\PycharmProjects/untitled1")
fileList = [name for name in items if name.endswith(".py")]
for cnt, fileName in enumerate(fileList, 0):
sys.stdout.write("[%d] %s\n\r" % (cnt, fileName))
choice = int(input("Select from [1-%s]: " % cnt))
choice_1 = input("Press any key to add more case or q to start running testsuite ")
run_list.append(fileList[choice])
print("These are the case/s you have selected so far :")
print(run_list)
selected_files = run_list
for x in run_list:
exec(open(c).read())
You may need to use importlib.
Check this link for an answer that might help you in this direction:
Exit an imported module without exiting the main program - Python
To allow the user to exit as needed you can do something like this inside the while True:
sys.stdout.write('Type file name (Enter to exit): ')
try:
sys.stdout.flush()
filename = sys.stdin.readline().strip()
if filename == '':
print('Exiting...')
break()
except:
exit()
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 3 years ago.
I need help to understand why my python variable is not changing?
Here is the code:
from tkinter import filedialog
from tkinter import *
selectedRootFolder = "" #<-------------------------------------here is the variable declared
# get any folder to be a root folder
def add_dir():
root = Tk()
root.withdraw()
dirname = filedialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)#<-----------------------here is the variable changed
# print the root folder
def print_root_dir_path():
print (selectedRootFolder) #<-----------------------------here is the variable empty -> =""
# in case a wrong number is taken
def invalid():
print("---------------------")
print ("INVALID CHOICE!")
print("---------------------")
# exit program
def exit_prog():
print ("Thank you, come back soon!")
exit()
# define the menu options
menu = {"1":("Choose Directory:", add_dir),
"2":("Print Root Directory Path",print_root_dir_path),
"9":("Exit",exit_prog)
}
while True:
# list the menu
for key in sorted(menu.keys()):
print (key + ":" + menu[key][0])
# pick a number
print("---------------------")
ans = input("Make A Choice: ")
print("---------------------")
#get the number, if none, call invalid function
menu.get(ans,[None,invalid])[1]()
This is just a part of the script, but it should be able to show my problem, which is that when I pick option 1, to choose a directory, it is successful, and it prints the selectedRootFolder, but when I choose option 2 after that, the printed value is just as declared in the beginning, empty.
I do not understand why is that, can u help me?
Thank you.
Edit 1:
Changed:
selectedRootFolder = print(dirname)
To:
selectedRootFolder = dirname
print("Here: " + selectedRootFolder)
Use global
Ex:
selectedRootFolder = ""
def add_dir():
global selectedRootFolder
selectedRootFolder = "Update"
add_dir()
print(selectedRootFolder)
Repl: https://repl.it/repls/SoreLankyAttributes
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 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.
i've written a tool in python where you enter a title, content, then tags, and the entry is then saved in a pickle file. it was mainly designed for copy-paste functionality (you spot a piece of code you like on the net, copy it, and paste it into the program), not really for handwritten content, though it does that with no problem.
i mainly did it because i'm always scanning through my pdf files, books, or the net for some coding example of solution that i'd already seen before, and it just seemed logical to have something where you could just put the content in, give it a title and tags, and just look it up whenever you needed to.
i realize there are sites online that handle this ex. http://snippets.dzone.com, but i'm not always online when i code. i also admit that i didn't really look to see if anyone had written a desktop app, the project seemed like a fun thing to do so here i am.
it wasn't designed with millions of entries in mind, so i just use a pickle file to serialize the data instead of one of the database APIs. the query is also very basic, only title and tags and no ranking based on the query.
there is an issue that i can't figure out, when you are at the list of entries there's a try, except clause where it tries to catch a valid index (integer). if you enter an inavlid integer, it will ask you to enter a valid one, but it doesn't seem to be able to assign it to the variable. if you enter a valid integer straightaway, there are no problems and the entry will display.
anyway let me know what you guys think. this is coded for python3.
main file:
#!usr/bin/python
from archive_functions import Entry, choices, print_choice, entry_query
import os
def main():
choice = ''
while choice != "5":
os.system('clear')
print("Mo's Archive, please select an option")
print('====================')
print('1. Enter an entry')
print('2. Lookup an entry')
print('3. Display all entries')
print('4. Delete an entry')
print('5. Quit')
print('====================')
choice = input(':')
if choice == "1":
entry = Entry()
entry.get_data()
entry.save_data()
elif choice == "2":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "3":
queryset = 'all'
result = entry_query('entry.pickle', queryset)
if result:
print_choice(result, choices(result))
elif choice == "4":
queryset = input('Enter title or tag query: ')
result = entry_query('entry.pickle', queryset)
if result:
entry = result[choices(result)]
entry.del_data()
else:
os.system('clear')
print('No Match! Please try another query')
pause = input('\npress [Enter] to continue...')
elif choice == "5":
break
else:
input('please enter a valid choice...')
main()
if __name__ == "__main__":
main()
archive_functions.py:
#!/bin/usr/python
import sys
import pickle
import os
import re
class Entry():
def get_data(self):
self.title = input('enter a title: ')
print('enter the code, press ctrl-d to end: ')
self.code = sys.stdin.readlines()
self.tags = input('enter tags: ')
def save_data(self):
with open('entry.pickle', 'ab') as f:
pickle.dump(self, f)
def del_data(self):
with open('entry.pickle', 'rb') as f:
data_list = []
while True:
try:
entry = pickle.load(f)
if self.title == entry.title:
continue
data_list.append(entry)
except:
break
with open('entry.pickle', 'wb') as f:
pass
with open('entry.pickle', 'ab') as f:
for data in data_list:
data.save_data()
def entry_query(file, queryset):
'''returns a list of objects matching the query'''
result = []
try:
with open(file, 'rb') as f:
entry = pickle.load(f)
os.system('clear')
if queryset == "all":
while True:
try:
result.append(entry)
entry = pickle.load(f)
except:
return result
break
while True:
try:
if re.search(queryset, entry.title) or re.search(queryset, entry.tags):
result.append(entry)
entry = pickle.load(f)
else:
entry = pickle.load(f)
except:
return result
break
except:
print('no entries in file, please enter an entry first')
pause = input('\nPress [Enter] to continue...')
def choices(list_result):
'''takes a list of objects and returns the index of the selected object'''
os.system('clear')
index = 0
for entry in list_result:
print('{}. {}'.format(index, entry.title))
index += 1
try:
choice = int(input('\nEnter choice: '))
return choice
except:
pause = input('\nplease enter a valid choice')
choices(list_result)
def print_choice(list_result, choice):
'''takes a list of objects and an index and displays the index of the list'''
os.system('clear')
print('===================')
print(list_result[choice].title)
print('===================')
for line in list_result[choice].code:
print(line, end="")
print('\n\n')
back_to_choices(list_result)
def back_to_choices(list_result):
print('1. Back to entry list')
print('2. Back to Main Menu')
choice = input(':')
if choice == "1":
print_choice(list_result, choices(list_result))
elif choice == "2":
pass
else:
print('\nplease enter a valid choice')
back_to_choices(list_result)
In the else, you call the main function again recursively. Instead, I'd do something like choice == "0", which will just cause the while loop to request another entry. This avoids a pointless recursion.