i understand that this error happens when a variable gets mentioned before its defined but "key" is assigned to its value. I started learning python a week ago so i am sorry if my question has a really simple answer.
the code:
from stat import SF_APPEND
import time
import random
keyType = 0
key = 0
deCypherKey = 0
operationType = 0
needToLoop = True
alphabet = "abcdefghijklmnopqrstuvwxyz "
print("ogulSifreleyici v1.0")
time.sleep(0.3)
print("Ipucu: Hem Sifrelemek Hem de Desifrelemek Icin Programi 2 Kere Calistirabilirsiniz")
def cypher():
message = input("Mesajini Gir:\n")
message = message.lower()
unCypheredMessageLength = len(message)
letterOfMessageInQueue = 0
keyStr = str(key)
keyStrInt = 0
whichOrderOfAlphabet = 0
whichLetterOfAlphabet = " "
whichDigitOfKey = 0
orderOfCypheredLetter = 0
cypheredLetter = "a"
cypheredMessageList = []
cypheredStr = ""
while unCypheredMessageLength > 0:
whichLetterOfAlphabet = alphabet[whichOrderOfAlphabet]
if message[letterOfMessageInQueue] == whichLetterOfAlphabet:
print("match")
print(whichOrderOfAlphabet, message[letterOfMessageInQueue], whichLetterOfAlphabet)
keyStrInt = int(keyStr[whichDigitOfKey])
orderOfCypheredLetter = whichOrderOfAlphabet + keyStrInt
if orderOfCypheredLetter > 26:
orderOfCypheredLetter = orderOfCypheredLetter - 26
cypheredLetter = alphabet[orderOfCypheredLetter]
cypheredMessageList.append(cypheredLetter)
unCypheredMessageLength = unCypheredMessageLength - 1
letterOfMessageInQueue = letterOfMessageInQueue + 1
whichOrderOfAlphabet = 0
whichDigitOfKey = whichDigitOfKey + 1
if whichDigitOfKey > 4:
whichDigitOfKey = whichDigitOfKey - 5
if len(cypheredMessageList) == len(message):
cypheredStr = "".join(cypheredMessageList)
print("Sifrelenmis Mesajiniz:\n" + cypheredStr)
time.sleep(1)
lastUserAnswer = input("1-Sifrele(Ayni Anahtar) 2-Sifrele(Farkli Anahtar)\n")
if lastUserAnswer == "1":
cypher()
if lastUserAnswer == "2":
key = input("Anahtar Giriniz(5 Haneli Sayi):\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
cypher()
cypher()
else:
whichOrderOfAlphabet = whichOrderOfAlphabet + 1
def deCypher():
deCypherMessage = input("Sifreli Mesajinizi Giriniz:\n")
operationType = input("1-Sifrele 2-DeSifrele\n")
while needToLoop == True:
if operationType == "1":
keyType = input("1-Anahtar gir(5 haneli sayi) 2-Rastgele Anahtar\n")
if keyType == "1":
key = input("Anahtar Giriniz:\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
cypher()
needToLoop = False
cypher()
if keyType == "2":
key = int(random.uniform(10000, 100000))
print("Anahtariniz: " + str(key))
cypher()
needToLoop = False
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
if operationType == "2":
deCypherKey = input("Anahtarinizi Giriniz:\n")
while len(str(deCypherKey)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
deCypher()
needToLoop = False
deCypher()
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
this is not exactly the reason you wrote, the fact is that the function cannot see variables that are outside the function. In order for the function to see them, you need to pass the variable as an argument to the function. That is, you need to change line 86 like this: cypher(key). But as you can see, this will give an error, because your function initially does not accept any arguments, in order to fix this we need to add the key argument in line 16 like this: def cypher(key):. There is the site where you can read more about it https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29
Related
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
I was programming a simple Connect 4 game however I need to add global variables
# Board(0:6, 0:7) : str (but ignore row 0 and column
0)
# ThisPlayer : str[1]
# GameFinished, WinnerFound : bool
# ColumnNumber : int
# ValidColumn, ValidRow : int
which im stuck on as I cant remember how to define global booleans etc (global variables are above)
when I run the code it gives me the error code (Board is not defined) how can I add the global variables so my program runs ?
Code is below
Board[0:6][0:7]
Blank = '.'
def InititialiseBoard():
Board = [[Blank for i in range(7)]
for j in range(6)]
def SetUpGame():
ThisPlayer = 'o'
GameFinished = False
def OutputBoard():
for Row in range(6 , 0 , -1):
for Column in range(7):
print(Board[Row][Column] , end = '')
print()
def ColumnNumberValud():
Valid = False
if ColumnNumber >= 1 and CalumnNumber <= 7:
if Board[6][ColumnNumber] == Blank:
Valid = True
return Valid
def ThisPlayerChoosesColumn():
print('Player ' + ThisPlayer + ' turn.')
while ColumnNumberValid == False:
print('Enter Valid Column Number')
ColumnNumber = int(input('Enter Column Number: '))
return ColumnNumber
def ThisPlayerMakesMove():
ValidColumn = ThisPlayerChoosesColumn()
ValidRow = FindNextFreePositionInColumn()
Board[ValidRow][ValidColumn] = ThisPlayer
def FindNextFreePositionInColumn():
ThisRow = 1
while Board[ThisRow][ValidColumn] != Blank:
ThisRow = ThisRow + 1
return ThisRow
def CheckHorizontalLineInValidRow():
for i in range(4):
if Board[ValidRow][i] == ThisPlayer and Board[ValidRow][i+1] == ThisPlayer and Board[ValidRow][i+2] == ThisPlayer and Board[ValidRow][i+3] == ThisPlayer:
WinnerFound = True
def CheckVerticalLineInValidRow():
if ValidRow == 4 or ValidRow == 5 or ValidRow == 6:
if Board[ValidRow][ValidColumn] == ThisPlayer and Board[ValidRow - 1][ValidColumn] == ThisPlayer and Board[ValidRow - 2][ValidColumn] == ThisPlayer and Board[ValidRow - 3 ][ValidColumn] == ThisPlayer:
WinnerFound = True
def CheckForFullBoard():
BlankFound = False
ThisRow = 0
while ThisRow !=6 or BlankFound == False:
ThisColumn = 0
ThisRow = ThisRow + 1
while ThisColumn != 7 or BlankFound == True:
ThisColumn = ThisColumn + 1
if Board[ThisRow][ThisColumn] == Blank:
BlankFound = True
if Blankfound == False:
print('Draw')
GameFinished = True
def CheckIfThisPlayerHasWon():
WinnerFound = False
CheckHorizontalLineInValidRow()
if WinnerFound == False:
CheckVerticalLineInValidColumn()
if WinnerFound == True:
GameFinished = True
print(ThisPlayer , 'Winner')
else:
CheckForFullBoard()
To use global variables:
global x
x = 1
def foo():
global x
x+=1
print(x)
foo()
print(x)
I would recommend avoiding global variables and use class variables instead.
class yourclass():
def__init__(self):
self.x = 1
def foo(self):
self.x+=1
def print_value(self):
print(self.x)
if __name__=='__main__':
test = yourclass()
test.print_value()
test.foo()
test.print_value()
I am making a language in python called PythonScript, which is a JavaScript and Python (not Python 3) mix.
I am adding variables, but when I do the following code I don't get the expected result.
var scuffles = hi!
I have tried to debug it, and as you will see in my code I made a debugging array, which I found to be empty. I looked up some tutorials, but none were covering what I am trying to do.
This is a portion of the file:
import os
import sys
programDebugingArray1 = []
functions = ["Console"]
functionCodes = [["out \"TEST\""]]
programVariables = {}
def lex(cm,stri,nums,toWake):
i = 0
if cm == "":
console()
elif cm == "var" or cm == "=":
pass
elif cm == "--vars":
print(programVariables)
elif cm == "--debugManual1":
print(programDebugingArray1)
else:
print("\""+cm+"\" was not recognized as a PythonScript command.")
console()
def console():
commandToRun = ""
tok = ""
string = ""
varValue = ""
newVarName = ""
Strings = []
Numbers = []
functionToCall = ""
state = 0
command = input()
for char in command:
tok += char
if state == 1:
string += char
elif state == 2:
if char == " ":
char = ""
newVarName += char
elif state == 3:
varValue += char
if (tok == "\"" or tok == "'") or (char == "\"" or char == "'"):
if state == 0:
state = 1
elif state == 1:
state = 0
string = string[0:len(string) - 1]
Strings.append(string)
string = ""
tok = ""
char = ""
elif tok == " ":
tok = ""
elif tok == "var" and state == 0:
state = 2
tok = ""
elif tok == "=" and state == 2:
state = 3
tok = ""
elif tok == "!" and state == 3:
programDebugingArray1.append(newVarName)
programDebugingArray1.append(varValue)
state == 0
programVariables[newVarName] = varValue
tok = ""
elif tok == "--vars" and state == 0:
commandToRun == "--vars"
tok = ""
elif tok == "--debugManual1" and state == 0:
commandToRun == "--debugManual1"
tok = ""
if commandToRun == "":
commandToRun = command
lex(commandToRun,Strings,Numbers,functionToCall)
console()
I expected the debug array to at least have something in it, but for some reason it and the variables dictionary is empty. There are no error messages or boots out of the console.
I defined the function 'actualizar_contadores()' and when called inside the main() function, its supossed to update the values of all the variables that were defined at the beginning of the script. First I didnt pass the actual variables as parameters to the function but that resulted in a "local variable referenced before assignment" error. Then I passed the references as parameters and that problem was gone but when I wanted to see the results they werent updated. I tried returning a tuple and assigning it to the variables in order to update their values, but it isnt working either and I get the local variable referenced before assignment error again. What can I do?
cant_motos = cant_autos = cant_camiones = 0
recaudacion_total = recaudacion_efectivo = recaudacion_telepeaje = 0
pasadas_primera_hora = pasadas_segunda_hora = pasadas_tercera_hora = pasadas_cuarta_hora = 0
cont_efectivo = cont_telepeaje = 0
patente_actual = ""
patente_nueva = ""
def actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones,recaudacion_efectivo,
recaudacion_telepeaje,cont_efectivo,cont_telepeaje):
if vehiculo == "Moto":
cant_motos += 1
if forma_de_pago == 1:
recaudacion_efectivo += 20
cont_efectivo += 1
elif forma_de_pago== 2:
recaudacion_telepeaje += 20
cont_telepeaje += 1
elif vehiculo == "Auto":
cant_autos += 1
if forma_de_pago == 1:
recaudacion_efectivo += 40
cont_efectivo += 1
elif forma_de_pago == 2:
recaudacion_telepeaje += 40
cont_telepeaje += 1
elif vehiculo == "Camion":
cant_camiones += 1
if forma_de_pago == 1:
recaudacion_efectivo += 80
cont_efectivo += 1
elif forma_de_pago == 2:
recaudacion_telepeaje += 80
cont_telepeaje += 1
def main():
# menu principal
opcion = pedir_opcion(menu_principal, 4)
while opcion != 4:
while opcion != 3:
if opcion == 1:
carga = pedir_opcion(menu_ingreso_datos, 2)
print("Ingrese la siguiente operacion: ")
opcion = pedir_opcion(menu_principal, 4)
elif opcion == 2:
if carga == 1:
diferencia = 0
tiempo_inicial = time.time()
while diferencia < 32:
contar_pasadas(diferencia, pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
tipo_vehiculo = pedir_opcion(menu_vehiculos, 3)
if tipo_vehiculo == 1:
vehiculo = "Moto"
elif tipo_vehiculo == 2:
vehiculo = "Auto"
elif tipo_vehiculo == 3:
vehiculo = "Camion"
forma_de_pago = pedir_opcion(menu_forma_de_pago, 2)
if forma_de_pago == 2:
patente = pedir_patente()
patente_nueva = definir_patente_nueva(patente)
actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones, cont_efectivo,
cont_telepeaje, recaudacion_efectivo,
recaudacion_telepeaje)
tiempo_final = time.time()
diferencia = tiempo_final - tiempo_inicial
elif carga == 2:
vehiculos = "Moto", "Auto", "Camion"
formas_de_pago = "Efectivo", "Telepeaje"
diferencia = 0
tiempo_inicial = time.time()
while diferencia < 4:
contar_pasadas(diferencia, pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
vehiculo = random.choice(vehiculos)
forma_de_pago = random.choice(formas_de_pago)
aviso_pasada = "{}. Pago con {}. Hora de pasada: {}.".format(vehiculo,
forma_de_pago,
str((round(diferencia / 60) + 1)))
if forma_de_pago == "Telepeaje":
patente = generar_patente()
aviso_pasada += "Patente: {}".format(patente)
patente_nueva = definir_patente_nueva(patente)
print(aviso_pasada)
actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones, cont_efectivo,
cont_telepeaje, recaudacion_efectivo,
recaudacion_telepeaje)
tiempo_final = time.time()
diferencia = tiempo_final - tiempo_inicial
time.sleep(random.randint(0,1))
pago_mayor_uso = forma_de_pago_mas_usada(cont_telepeaje, cont_efectivo)
promedio_pasadas_por_hora = round((cant_autos + cant_motos + cant_camiones) / 4, 2)
hora_pico = definir_hora_pico(pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
recaudacion_total = recaudacion_efectivo + recaudacion_telepeaje
pases_totales = cant_motos + cant_autos + cant_camiones
print("Ingrese la siguiente operacion: ")
opcion = pedir_opcion(menu_principal, 4)
main()```
You should not pass global vars to functions by parameters. Use global keyword.
Here is an example:
x = 10
y = 20
def myFunc():
global x
x = 3
y = 2
myFunc()
print(x, y) # output: 3 20
I am not sure why do i get this error from the console:
<<
print stirngp[state[i][j]]
^
SyntaxError: invalid syntax
<<
Furthermore it seems that the IDE put a red close on the following code line
line = raw_input("Enter:")
I am not sure what did i do wrong, the following code is as shown below
def isTerminal(state):
stateT = zip(*state)
for i in range(3):
if all(state[i][0] == j for j in state[i]) and state[i][0] != 0:
return state[i][0]
if all(stateT[i][0] == j for j in stateT[i]) and stateT[i][0] != 0:
return stateT[i][0]
if (state[0][0] == state[1][1] == state[2][2]) or \
(state[0][2] == state[1][1] == state[2][0]):
if state[1][1] != 0:
return state[1][1]
for i in range(3):
if 0 in state[i]:
return None
return 0
def succ(state):
# print state
countX = 0
countO = 0
for i in range(3):
for j in range(3):
if state[i][j] == 1: countX = countX + 1
if state[i][j] == -1: countO = countO + 1
if countX > countO:
player = "MIN"
else:
player = "MAX"
succList = []
v = {"MIN":-1,"MAX":1}
for i in range(3):
for j in range(3):
if state[i][j] == 0:
succ = [k[:] for k in state]
succ[i][j] = v[player]
succList = succList + [succ]
# print succList
return succList
def nextplay(player):
if player == "MIN":
return "MAX"
else:
return "MIN"
def minimax(state,alpha,beta,player):
value = isTerminal(state)
if value != None:
# print "TERMINAL:", state, value, player
return value
if player == "MIN":
for y in succ(state):
beta = min(beta, minimax(y,alpha,beta,"MAX"))
if beta <= alpha: return alpha
return beta
if player == "MAX":
for y in succ(state):
alpha = max(alpha, minimax(y,alpha,beta,"MIN"))
if alpha >= beta: return beta
return alpha
def printing(state):
p = {-1:"O",0:".",1:"X"}
for i in range(3):
for j in range(3):
print p[state[i][j]],
print ""
print ""
def main():
state = [[0,0,0],
[0,0,0],
[0,0,0]]
val = isTerminal(state)
while val == None:
line = raw_input("Enter:")
x = line.split(",")
a = int(x[0]); b = int(x[1])
state[a][b] = 1
if isTerminal(state) != None:
printing(state)
return
# determine which successive state is better
succList = succ(state)
succValList = []
for i in succList:
succValList = succValList + [(minimax(i,-1,1,"MAX"),i)]
succValList.sort(key=lambda x:x[0])
state = succValList[0][1] # can also randomly choose other states of the same minimax value
printing(state)
val = isTerminal(state)
if __name__ == '__main__':
main()
As far as i know you can't use raw_input() in Python 3. It's been changed to just input()
http://docs.python.org/dev/whatsnew/3.0.html
also what is stringp? is it an existing list?
if so then state[i][j] MUST return an integer so you can retrieve the item at that index of stringp[]