I cannot find the error in my Python Code [duplicate] - python

This question already has answers here:
UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)
(14 answers)
Closed 6 years ago.
I am (attempting) to make a hacking game like Hack Run or Hacknet. But only the terminal. I get this error when I try to print the variable 'currentip' at line 86 ("print("You are currently at " + currentip + ".")"):
UnboundLocalError: local variable 'currentip' referenced before assignment
This looks like a simple error but I cannot figure it out. I have assigned it. Multiple times. Maybe I am reading the order execution wrong but I can't find any info that says I am doing it wrong...
Any ideas for cleaning up and making it neater/better is also very much appreciated.
import os
import random
from time import sleep
os.system("cls")
save = {}
ips = {"1337.1337.1337.1337": "Cheater's Stash"}
shells = []
storyips = ["Bitwise Test PC"]
currentip = "1.1.1.1"
homeip = "1.1.1.1"
def resetip():
ip1 = random.randint(1, 999)
ip2 = random.randint(1, 999)
ip3 = random.randint(1, 999)
ip4 = random.randint(1, 999)
homeip = str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
if homeip in ips:
resetip()
else:
ips[homeip] = "Your Computer"
currentip = homeip
def storyreset():
for x in storyips:
ip = (0, 0, 0, 0)
ip1 = random.randint(1, 999)
ip2 = random.randint(1, 999)
ip3 = random.randint(1, 999)
ip4 = random.randint(1, 999)
ip = str(ip1) + "." + str(ip2) + "." + str(ip3) + "." + str(ip4)
if ip in ips:
storyreset()
else:
ips[ip] = x
def start():
os.system("cls")
print("Python 3.5, HackSim 1.1")
print("")
print("Loading modules...")
print("")
sleep(1)
print("OS Loaded.")
sleep(0.5)
print("HELP Loaded.")
sleep(0.5)
print("FILE USE Loaded.")
sleep(1)
print("CONNECTIONS Loaded.")
sleep(0.5)
print("UTILS Loaded.")
sleep(0.5)
print("HACKS Loaded.")
print("")
sleep(1)
print("Initiating command line...")
sleep(1)
commandline()
def usecommand(c):
if c == "reboot":
print("Rebooting...")
sleep(3)
start()
elif c == "clear":
os.system("cls")
elif c == "quit":
quit()
elif c == "forkbomb":
del ips[currentip]
if homeip in ips:
currentip = "Your Computer"
else:
resetip()
currentip = "Your Computer"
elif "connect " in c:
if c[8:] in ips:
connectip = ips[c[8:]]
print("Connecting to ", connectip, " ", c[8:], "...")
currentip = connectip
else:
print("This ip does not exist.")
elif c == "connect":
print("You are currently at " + currentip + ".")
print("The syntax of this command is: connect <ip>.")
else:
print("Invalid command. Either the command does not exist or check the required syntax.")
def commandline():
while True:
command = input("> ")
usecommand(command)
storyreset()
resetip()
start()
Thanks!

The problem is that you have global variables in your code and you are trying to access them from inside the function without first declaring them global. You need to put a line global currentip at the beginning of your usecommand function.
Also note that if you only used the variable currentip in your function it would work, but if you are both using it and assigning it within the same function the interpreter assumes it is a local variable you are using. Take a look at this:
x = 10
def f():
print x
def f2(arg):
if arg:
x = 20
else:
print x
Running function f() will print 10, but running function f2(0) will produce an error because the interpreter is once again unsure of whether the variable you are using is local or global and assumes it is a local one.
HTH.

Related

My python code stops working after a few iteration

I'm currently learning how to code with python, and I thought the best way would be learning by doing so I tried to create a voice assistant but it just stops working after a few iterations.
The code below isn't very efficient nor clean, but it works except for the part that it stops after a few iterations of listening.
there are no error mesages nor does the code actually stop it just doesn't do anything
thank you for every suggestion in advance
import speech_recognition as sr
import pyttsx3
import datetime as dt
# import wikipedia
# import webbrowser
import os
# import time
# import subprocess
# import ecapture as ec
# import wolframalpha
# import json
# import requests
# from gtts import gTTS
import random as ran
from docx import Document
document = Document()
note_new = ""
note_complete = ""
adding_more = True
second = dt.datetime.now().second
minute = dt.datetime.now().minute
hour = dt.datetime.now().hour
hour_str = str(hour)
minute_str = str(minute)
second_str = str(second)
time = hour_str + ":" + minute_str + ":" + second_str + " "
# initialising the text to speech engine
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)
# <editor-fold desc="Listening to the Users input">
# listening to the Users input
statement = ""
def listen():
global statement
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
statement = r.recognize_google(audio, language='en-in')
except Exception as e:
# speak("Pardon me, please say that again")
return "None"
return statement
# </editor-fold>
# <editor-fold desc="Talking">
def talk(text):
engine.say(text)
engine.runAndWait()
# </editor-fold>
# <editor-fold desc="Key Words">
# KeyWord Functions
def hello():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Hello Sir, welcome home.")
talk("Hello Sir, welcome home.")
elif random_text == 2:
print("Hello, welcome home.")
talk("Hello, welcome home.")
elif random_text == 3:
print("Welcome back.")
talk("Welcome back.")
def minecraft():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Minecraft...")
talk("Initialising Minecraft")
elif random_text == 2:
print("Minecraft coming right up...")
talk("Minecraft coming right up")
elif random_text == 3:
print("Starting Minecraft")
talk("Starting Minecraft")
os.startfile("C:\Spiele\Minecraft\MinecraftLauncher.exe")
def chrome():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Chrome...")
talk("Initialising Chrome")
elif random_text == 2:
print("Chrome coming right up...")
talk("Chrome coming right up")
elif random_text == 3:
print("Starting Chrome...")
talk("Starting Chrome")
os.startfile("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")
def valorant():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Valorant...")
talk("Initialising Valorant")
elif random_text == 2:
print("Valorant coming right up...")
talk("Valorant coming right up")
elif random_text == 3:
print("Starting Valorant...")
talk("Starting Valorant")
os.startfile("C:/Spiele/Riot Games/VALORANT/live/VALORANT.exe")
def aim_lab():
random_text = ran.randint(1, 3)
if random_text == 1:
print("Initialising Aim Lab...")
talk("Initialising Aim Lab")
elif random_text == 2:
print("Aim Lab coming right up...")
talk("Aim Lab coming right up")
elif random_text == 3:
print("Starting Aim Lab...")
talk("Starting Aim Lab")
os.startfile("steam://rungameid/714010")
def clock():
global second
global minute
global hour
global hour_str
global minute_str
global second_str
global time
second = dt.datetime.now().second
minute = dt.datetime.now().minute
hour = dt.datetime.now().hour
hour_str = str(hour)
minute_str = str(minute)
second_str = str(second)
time = hour_str + ":" + minute_str + ":" + second_str + " "
print("It's " + hour_str + " hours and " + minute_str + " minutes")
talk("It's " + hour_str + " hours and " + minute_str + " minutes")
def note():
global adding_more
global note_new
global note_complete
print("How should i call the note?")
talk("How should i call the note?")
listen()
note_name = statement
while adding_more:
print("Ok you can start talking:")
talk("Ok you can start talking:")
listen()
note_new = statement
print("new: " + note_new)
note_complete = note_complete + " " + note_new
print("new: " + note_complete)
print("Do you want to add more?")
talk("Do you want to add more?")
listen()
if "yes" in statement.lower():
adding_more = True
if "no" in statement.lower():
adding_more = False
print("printing...")
talk("printing..")
note_name_txt = note_name + ".txt"
note_name_complete = note_name_txt
f = open(note_name_complete, "w+")
f.write(note_complete)
f.close()
print("ready")
talk("ready")
print("should i open the note?")
talk("should i open the note?")
listen()
if "yes" in statement.lower():
note_name_complete = str(note_name_complete)
note_name_path = note_name_complete.replace(" ", "_")
os.startfile("D:/Python/Projekts/Jarvis/" + note_name_complete)
def dice():
number = 6
print("What sould be the range")
talk("What sould be the range")
listen()
try:
number = int(statement)
except:
print("I could not understand you sorry Sir!")
dice()
random_number = ran.randint(1, number)
print("The D " + str(number) + " says " + str(random_number))
talk("The D" + str(number) + "says" + str(random_number))
def stop():
global hour
if hour <= 12:
print("have a good day!")
talk("have a good day!")
if 19 >= hour < 12:
print("Goodbye")
talk("bye")
if hour > 19:
print("Goodnight!")
talk("Goodnight")
quit()
# </editor-fold>
if __name__ == '__main__':
while True:
statement = " "
listen()
print(statement)
command = statement.lower()
if "jarvis" in command:
if "hello" in command:
hello()
if "minecraft" in command:
minecraft()
if "chrome" in command:
chrome()
if "valorant" in command:
valorant()
if "time" in command or "clock" in command:
clock()
if "note" in command:
note()
if "dice" in command:
dice()
if "aim" in command or "lab" in command:
aim_lab()
if "stop" in command or "bye" in command or "goodbye" in command or "goodnight" in command:
stop()
If you report:
stops working after a few iterations
Then I would look for the loop (where iterations happen usually). I found the only obvious loop in the main block:
Shorten the loops
if __name__ == '__main__':
while True:
statement = '' # initialize as empty string
listen()
print(statement)
execute_command(statement.lower())
Extracted your command switch into a method execute_command:
def execute_command(command):
if "jarvis" in command:
if "hello" in command:
hello()
if "minecraft" in command:
minecraft()
if "chrome" in command:
chrome()
if "valorant" in command:
valorant()
if "time" in command or "clock" in command:
clock()
if "note" in command:
note()
if "dice" in command:
dice()
if "aim" in command or "lab" in command:
aim_lab()
if "stop" in command or "bye" in command or "goodbye" in command or "goodnight" in command:
stop()
Then watch out to the understood command that is printed.
Which command was the last printed before the loop stopped?
Design pure functions (returning a value)
This goes hand in hand with another common programming advice:
Don't use global variables!
def listen():
statement = '' # remove global, make it local and return
r = sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
audio = r.listen(source)
try:
statement = r.recognize_google(audio, language='en-in')
except Exception as e:
# speak("Pardon me, please say that again")
return "None"
return statement # you had the return already; use it!
Then your main (and other usage locations) would change to:
if __name__ == '__main__':
while True:
statement = listen() # use the return
print(statement)
execute_command(statement.lower())

How do I import my own object in vs studio code?

I'm trying to import the Human object I created for my contact book program and im doing it in VS Studio Code but it gives me an error:
Import "Human" could not be resolved
I tried to make the program in pycharm instead and it imported just fine and I even finished the program. And while looking around for a solution for the VS Studio Code version, I found some stuff like adding
"python.autoComplete.extraPaths": ["./**"],
to my settings.json and I did and a few other things i found on google, but it nothing helped.
VS Studio Code:
from Human import Human
#from Contact_Book_Project.Human import Human # auto generated, Not sure how it is different but i do have these 2 classes in a folder called Contact_Book_Project
book = []
def main():
while (True):
choice = int(input("Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
def addPerson(person):
book.append(person)
if __name__ == "__main__":
main()
class Human:
def __init__(self, name, phone_Number, address):
self.Name = name
self.Phone_Number = phone_Number
self.Address = address
def getName(self):
return self.Name
def getPhoneNumber(self):
return self.Phone_Number
def getAddress(self):
return self.Address
PyCharm Code:
from Human import Human
book = []
def main():
while (True):
try:
choice = int(input(
"Press 1 to add someone to your Contact Book\n2 to remove someone from the book\n3 to find someone\n4 to "
"list everyone\n5 to exit\n"))
if (choice == 5):
break
elif (choice == 1):
name = input("Name: ")
phoneNum = input("Phone Number: ")
address = input("Address: ")
person = Human(name, phoneNum, address)
addPerson(person)
elif (choice == 2):
name = input("Enter name of person to remove: ")
temp = 0
for i in book:
if i.getName() == name:
book.pop(temp)
print(i.getName() + " removed.")
break
temp += 1
# elif (choice == 3):
# name = input("Enter name of person to check if they are in your contact book and retrieve their "
# "information: ")
#
# if name in book:
# temp = book.__getitem__(name)
# print(
# "Name: " + temp.getName() + "\nPhone Number: " + temp.getPhoneNumber() + "\nAddress: " + temp.getAddress())
# else:
# print(name + " does not exist in your contact book.")
elif (choice == 4):
for p in book:
print(
"Name: " + p.getName() + "\nPhone Number: " + p.getPhoneNumber() + "\nAddress: " + p.getAddress() + "\n")
except ValueError:
print("\nInvalid input.\n")
def addPerson(person):
book.append(person)
if __name__ == '__main__':
main()
both are using the same Human class. How can I fix this? Why is it throwing an error in VS Studio but work in Pycharm?
Maybe try directing VS Code to the exact location of the Human module:
import sys
sys.path.append('file path to Human.py') # Add file path to 'Human.py' here
from Human import Human

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.

Python 3.1.1 - Assign random values to a function

I need a way to assign random values to a function, call the function and print the value to the screen.
When I run the code as it is, the enemy's attack and user's defense does not get recalculated. What can I do to have Python recalculate these variables every time the function is called?
import random
enemyName = "Crimson Dragon"
def dragonAtk():
return random.randint(5,10)
def userDef():
return random.randrange(8)
userHp = 100
userName = input("What is your name? ")
enemyAttackname = "Fire Blast"
def enemyAttacks():
global battleDmg
global userHp
global enemyAtk
global userDef
enemyAtk = dragonAtk()
userDef = userDef()
print (">>> " + enemyName + " attacks " + userName + " with " + enemyAttackname + "!")
if enemyAtk < userDef:
print (">>> " + userName + " successfully defended the enemy's attack!")
elif enemyAtk == userDef:
print (">>> " + userName + " successfully parried the enemy's attack!")
else:
battleDmg = enemyAtk - userDef
userHp -= battleDmg
print (">>> " + userName + " takes " + str(battleDmg) + " DMG! "\
+ userName + " has " + str(userHp) + " HP remaining!")
enemyAttacks()
input()
enemyAttacks()
input()
This is my result
What is your name? Murk
>>> Crimson Dragon attacks Murk with Fire Blast!
>>> Murk takes 6 DMG! Murk has 94 HP remaining!
Traceback (most recent call last):
File "C:\Users\Junior\Desktop\python projects\test", line 37, in <module>
enemyAttacks()
File "C:\Users\Junior\Desktop\python projects\test", line 22, in enemyAttacks
userDef = userDef()
TypeError: 'int' object is not callable
>>>
So, I see it ran once through enemyAttacks(), but the second time gave me an error. Not sure what to make of it. Any thoughts?
Here:
userDef = userDef()
You have overridden your function. Thus, when you call the function again, you are trying to call the function, but you have an integer instead (hence the error).
Rename your variable to another name so you don't override your function.

Python Not Running Code [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wrote a python script which just stopped working suddenly. I'm not sure why so any help would be appreciated. The console just doesn't display anything. I called the function start on the bottom but no luck.
import random
year = 1
our_score = 0
their_score = 0
games_played = 0
#opponent's strategy:
def op_strategy():
for i in range (0,1):
rand = random.randint(0,1)
if rand == 0:
return "war"
if rand == 1:
return "peace"
def start():
global our_score, their_score, year
print "====="
print "Year " + str(year)
print "Our Score: " + str(our_score)
print "Their Score: " + str(their_score)
print ""
strategy = raw_input("What is your strategy this year? ")
inputs(strategy)
def inputs(strategy):
our_score = 0
global our_score, their_score, year
if str(strategy) == "peace" or str(strategy) == "war":
print "You chose: " + str(strategy)
op_strat = str(op_strategy())
print "They chose: " + op_strat
if str(strategy) == "war" and str(op_strat) == "war":
print ">>> Everyoner to arms!"
our_score = our_score + 1
their_score = their_score + 1
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "peace":
print ">>> Peace for everyone!"
our_score = our_score + 3
their_score = their_score + 3
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "war":
print ">>> They crushed us!"
our_score = our_score
their_score = their_score + 5
year = year + 1
elif str(strategy) == "war" and str(op_strat) == "peace":
print ">>> We crushed them!"
our_score = our_score + 5
their_score = their_score
year = year + 1
if str(year) == "11":
print "====="
print "Final"
print str(our_score)
print str(their_score)
if our_score > their_score:
print ">>>>> We win! <<<<<"
if their_score > our_score:
print ">>>>> They win! <<<<<"
if their_score == our_score:
print ">>>>> It's a tie! <<<<<"
play = raw_input("Play again?")
if play == "y":
start()
if play == "n":
pass
else:
play = raw_input('Invalid response. Please enter "y" or "n".')
if str(strategy) != "peace" and str(strategy) != "war":
strategy = raw_input('Invalid strategy. Enter "peace" or "war": ')
inputs(strategy)
start()
start()
The code is executing, but it is stuck at the raw_input call, and not printing until it completes, which of course the user does not know to do because nothing has printed.
The buffer is not automatically flushed. If you start python with the -u option, the buffer will be flushed with the raw_input call, and the prompt will be apparent.
Load this up in Idle and you'll see the following error:
SyntaxError: name 'our_score' is assigned to before global declaration (, line 1)
One these lines:
def inputs(strategy):
our_score = 0
global our_score, their_score, year
As detailed here:
If the global statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level
namespace... i.e. the namespace of the module containing the code block
You've assigned to a local variable our_name and then you're telling the function to use a global variable of the same name. There should be no problems after fixing this.

Categories