Why is my python global variable not changing? [duplicate] - python

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

Related

multiple global statements within function elifs

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)

How do I get a python program to rerun itself [duplicate]

This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()

Python - If statement not functioning inside def() function

I hope someone can help me with this issue.
from tkinter import *#This enables me to use the tkinter commands
window=Tk()#This declares the window
window.title("Binary-Denary converters")#This defines the name of the window
loop=1
def selection():
global submitbutton
global variable
global choice#This declares the variable so it can be used anywhere in the code
label1=Label(window,text="Submit 1 for D-B \nSubmit 2 for B-D ")#This tells the user what to input
label1.pack()
variable= StringVar(window)
variable.set("")
choice=OptionMenu(window, variable,"1 ", "2 ")
choice.pack()
submitbutton=Button(window, text="Submit",command=getinput)
submitbutton.pack()
def getinput():
global variable
global userinput
userinput=variable.get()#This takes the users input and assigns it to a variable
print(userinput)
if userinput =="1":
DToB()
else:
BToD()
def DToB():
display1=Label(window, text="D to B")
display1.pack()
submitbutton.destroy()
def BToD():
display2=Label(window, text="B to D ")
display2.pack()
submitbutton.destroy()
selection()
The user has a drop down list, and selects 1 for DToB and 2 for BToD, the program is able to identify the number that the user chose and I checked it does this by printing userinput. I have also checked and it is a str value that comes from this drop down list I confirmed this by adding userinput to userinput which gave me 1 1 instead of 2 if it was an int.
The issue is with the if statement " if userinput =="1" " in the getinput() function which even when userinput does = 1 just goes with what is in the else part of the statement.
I have used if statements like this in very similar codes before so I cannot understand what I have done wrong.
Here is some pictures of the program running
pic1 pic2
The problem is this line:
choice = OptionMenu(window, variable, "1 ", "2 ")
When the user chooses 1, the value of the StringVar is actually set to "1 ", not "1". Either change the values of the option menu or change if userinput == "1" to if userinput = "1 ", and your code will behave as expected.

Local variable 'first' referenced before assignment [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Closed 7 years ago.
I get a Local variable 'first' referenced before assignment error when I run my code.
def start():
global a
a = [" "," "," "," "," "," "," "," "," "]
global first
first = randrange(2)
def reverse():
if first == 1:
first = 0
else:
first = 1
if first == 1:
turn = "X"
else:
turn = "O"
That is just a part of my code where the error occurs. However when I paste the code into IDLE it works no problem so I don't know why this is happening.
Anyways, my full code (unfinished Tic Tac Toe):
from os import name
from os import system
from random import randrange
from time import sleep
def cls():
system(['clear','cls'][name == 'nt'])
def start():
global a
a = [" "," "," "," "," "," "," "," "," "]
global first
first = randrange(2)
def reverse():
if first == 1:
first = 0
else:
first = 1
if first == 1:
turn = "X"
else:
turn = "O"
while True:
reverse()
cls()
printBoard()
print ""
print "Its %s's turn." % (turn)
print ""
move = raw_input("Enter your move (1-9): ")
if move.isdigit() == True:
move = int(move)
if move in range(9):
move = move - 1
if a[move] == " ":
a[move] = turn
else:
print "Incorrect move: Place taken"
reverse()
sleep(2)
else:
print "Incorrect move: Number out of range"
sleep(2)
else:
print "Incorrect move: Move not a number"
sleep(2)
def printBoard():
cls()
print a[0],"|",a[1],"|",a[2]
print "---------"
print a[3],"|",a[4],"|",a[5]
print "---------"
print a[6],"|",a[7],"|",a[8]
start()
Python scans a function body for any assignments, and if they aren't explicitly declared global, then it creates a local scope variable for that name. Because you assign to first in your reverse() function, and you haven't explicitly declared first to be global within that function's scope, python creates a local variable named first that hides the global one.
It doesn't matter that the assignment comes after the comparison; python implicitly declares all local variables at the beginning of the function.
To fix this you can declare first to be global within the reverse() function, but as others have said, globals should be avoided when possible.

Nothing executes in code [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Python Application does nothing
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv("HOSTNAME")
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
The input() is supposed to execute and it stopped working after changing something I dont remember
It's coded under Python 3.1.2 with Windows 7, I know the Unix Hostname global variable is wrong
I know userinput does nothing, I want to get this part working before I continue on
Thanks
It outputs nothing
You define a class and two functions, but you don't seem to call any of them anywhere. Are you missing a call to MainShellLoop() in the end?
I think you need a call to MainShellLoop.

Categories