python - multiple global statements within function elifs -


the program first asks user if they'd load own file or use the file provided script.

filename=0 def first(filename):     print('please select:')     print('run program now? press "1"')     start = int(input('load own list , run program? press "2": '))      if start ==1:         global filename         filename = 'file.txt'     elif start ==2:         import tkinter tk         tkinter import filedialog          root = tk.tk()         root.withdraw()         global filename         filename = tkinter.filedialog.askopenfilename()     else:         print("you didn't enter valid selection!")         first(filename)     main() 

i'm using function should call correct file based on user input.

def guess(real):     wordlist = filename     open(wordlist, 'r') in_file: 

error:

errorsyntaxerror: name 'filename' assigned before global declaration 

this worked earlier when had user input , elif statements within

def guess(real): 

although wanted call separately , that's why have user input in it's own function.

you don't need use return global variables, avoid using global variables if possible. might want read "why global variables evil" more details.

a simplified version of code provided shown below using return , passing result function avoid using global variables:

def first():     while true:         print('please select:')         print('run program now? press "1"')         start = int(input('load own list , 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 valid selection!")  def second(filename):     print (filename)  filename = first() second(filename) 

Comments

Popular posts from this blog

'hasOwnProperty' in javascript -

python - ValueError: No axis named 1 for object type <class 'pandas.core.series.Series'> -

java - How to provide dependency injections in Eclipse RCP 3.x? -