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.
Related
Good Evening All,
I have been working on my first self directed project and have run into a bit of a snag. The program calculates what a character would have to roll to hit another based on their THAC0 and AC. The two scores in question are kept in a pair of dictionaries. If something is entered that is not in the dictionary I want the program to let whoever is operating it know. I've managed to get it to produce an error code, but I still get a KeyError. How do I get it to stop doing that?
defender = input("Who are they attacking?")
dict_thaco = {"Serena" : 19, "Morris" : 19}
if aggressor in dict_thaco:
pass
else:
print("I don't know that attacker")
dict_ac = {"Serena" : 6, "Morris" : -1}
if defender in dict_ac:
pass
else:
print("I don't know that defender")
def thaco_calc(thaco, ac):
to_hit = thaco - ac
return to_hit
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
Perhaps you need something like
...
try:
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
except KeyError as e:
print(e)
I'm brand new to Python and I'm trying to create a very simple code where every time the user presses enter, they earn five points, followed by the line printing how many points they currently have. The code looks like this:
pointsEarned = 0
alien_0 = {"points":5}
new_points = alien_0["points"]
def kill():
input("Press enter to kill an alien!")
pointsEarned = pointsEarned + 5
killed()
def killed():
print("You just earned " + str(new_points) + " points!")
print("Current points: " + str(pointsEarned))
kill()
kill()
However, when I run this code, it gives me this error:
UnboundLocalError: local variable 'pointsEarned' referenced before assignment
I don't understand this, as I defined pointsEarned outside of either function beforehand. How do I fix this?
pointsEarned = 0
alien_0 = {"points":5}
new_points = alien_0["points"]
def kill():
global pointsEarned
input("Press enter to kill an alien!")
pointsEarned += 5
killed()
def killed():
print("You just earned " + str(new_points) + " points!")
print("Current points: " + str(pointsEarned))
kill()
kill()
I am trying to access a variable within a function in a class and print it. Whenever I try I keep getting the error: AttributeError: 'NoneType' object has no attribute 'job_ID'.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.temp)))
print("Average priority: " + str(q.average))
if 'modify' in line:
q.modify(line)
print("Modified job " + q.current.job_ID)
The error is coming from the last print statement in this code.
This is the function within the class that is being used here:
def modify(self, x): # need to fix printing bug
self.current = self.head
while self.current != None:
if x[1] in self.current.get_data():
self.current.data[2] = x[2]
self.current.data[3] = x[3]
break
# print("Modified job " + current.job_ID)
else:
# print('The job details cannot be modified.')
pass
self.current = self.current.get_next()
The exit condition for the loop in the modify function that you have provided is self.current == None.
When you call modify() in this last conditional statement:
if 'modify' in line:
q.modify(line) // here
print("Modified job " + q.current.job_ID)
You are making q.current evaluate to None. Therefore, the reason why you are getting an AttributeError is because q.current is None, which has no such attribute called job_ID.
To fix your problem, you must ensure that q.current is not None before printing q.current.job_ID. I can't give you any help beyond this, since I don't know what the purpose of your program is.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
TypeError: ‘module’ object is not callable
This is my very first Python attempt, just trying to regain basic programming knowledge after a 10 year silence in a, for me, new language, Python. The basic idea is a tiny battly engine which decides the better hit. The bugging code is next.
self.__power = self.__att*random(2,4)/dier.__defn
As my python knowledge is extremely basic, I'm rather scared of saying the right things so Im gonna put my code down below (47 lines), you..ll notice it is really transparant so I dont suspect this will give any problem. The errorline is 16. I tried renaming the att variable to atta as well as some repositionings though new bugs come, I solve them and in the end its always the same error on the same line.
class Character:
def __init__(self,name="", att=0,defn=0,lvl=0,leven=0,exp=0, power=0):
self.__att = att
self.__defn = defn
self.__lvl = lvl
self.__leven = leven
self.__name = name
self.__xp = exp
self.__power = power
def batl(self):
import random
while self.__lvl <= 3:
dier = Character("Anaconda",1,1,50,1,0,0)
print "You encountered an " + dier.__name + " and fight it."
**self.__power = self.__att*random(2,4)/dier.__defn**
dier.__power = (dier.__att*random(1,4))/self.__defn
if self.power > dier.power:
growth = dier.__lvl*dier.__atta
groei()
else:
dmg = dier.lvl*dier.att
leven = leven-dmg
if leven < 0:
print "Alas, you're done for."
exit()
else:
print "You took " + dmg + "damage and have " + leven + "life left."
def groei(self):
if (growth+exp) > 100:
lvl += 1
exp = growth-100
print "You won and gained " + str(growth) + " and grew from level " + str(lvl-1) + " to level " + str(lvl) + "."
else:
exp = growth + exp
print "You won and gained " + str(growth) + "."
def main():
hero = Character("Nevery",2,1,2,100,0,0)
hero.batl()
if name == 'main':
main()
As you can see ive got my character class, in which i have defined the battle() method and the groei() method, very basic. Can anyone point me what I'm missing out on, been looking at it for hours. Thanks in Advance
random is the module, not the function. You need to call random.random. You could also from random import random, but I'd go with the first option in this case.
Use random.random() instead of random?