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)
Related
I am working on a program that can search wikipedia given an input like: "Who is Elon Musk" - however, with his specific example (and others), when the variable is placed into wikipedia.summary(string), it removes the "l" in "Elon Musk". Attached is my function:
import wikipedia
import spacy
def search_wiki(self, search):
nlp = spacy.load('en_core_web_sm')
doc = nlp(search)
subject_phrase = get_subject_phrase(doc)
try:
results = wikipedia.page(str(subject_phrase)) #removes here
final = results
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.PageError:
results = wikipedia.search(str(subject_phrase))
print("\nDid you mean " + results[0] + "?\n")
possible = results[0]
if input() == "yes":
final = possible
print(final) #prints "Elon Musk"
print(wikipedia.summary(final, sentences=1)) #removes here too
else:
print("\nThese are the other searches that came up for " + str(subject_phrase) + ":\n")
for r in results:
print(r)
print("\nPlease type the result you want me to search for:\n")
final = input()
print(wikipedia.summary(final, sentences=1))
except wikipedia.exceptions.DisambiguationError as e:
print("I couldn't find anything for " + str(subject_phrase) + ". Here are some related results:")
for o in e.options:
print(o)
print("\nWhich of these did you mean?")
final = input()
print(wikipedia.summary(final, sentences=2))
print("\nWould you like to hear more about " + final + "?\n")
if input() == "yes":
print("\nYou can read more about " + final + " at " + wikipedia.page(final).url + "\n")
entry = wikipedia.summary(final, sentences=3)
return lambda: entry, True
else:
entry = wikipedia.summary(final, sentences=1)
return lambda: entry, False`
I am pretty stuck, I have the variable printing right before the call to wikipedia.summary(string), so I know that the variable is not changing on my end (or at least I think).
def room1(phone_charge):
phone_charge = 5
import random
randNum = random.randint(1,5)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return(positve)
I need to add positive to another function
def room5(phone_charge):
import random
randomNUM = random.randint(1,30)
positve2= str(phone_charge + randomNUM)
print("Your phone is now " + positve2 + " % charged\n")
return(positve2)
I need to add postive to the room5 variable postive2
I tried returning variables and putting them in the next function but then my code that was written behind where I entered the returning variable it was no longer highlighted
Since the two functions return their values, you can add them together after calling.
p1 = room1(phone_charge)
p5 = room5(phone_charge)
print(f"Total is {p1 + p5}")
Since the two functions have the same functionality use one function with an extra parameter.
import random
def room(phone_charge, rand_range):
randNum = random.randint(1,rand_range)
print("An outlet! You quickly plug in your phone, but the wiring in the house is faulty and soon shorts out.\n")
positve = str(phone_charge + randNum)
print("Your phone is now " + positve + " % charged\n")
return positve
room1 = room(5, 5)
room5 = room(10, 30)
total = room1 + room5
I'm making a curency converter, time converter and weather app for an year 12 computer sciences project. Im unable to interrupt the loop that is being used for the main menu/location selector.
Can anyone help?
The code is below.
##This program is intended to help travellers with date and currency conversions ##
##Changelog----->##
##V1 - Include code for Forex Converter, code modified from - https://www.w3schools.in/python/examples/real-time-currency-converter##
##V2 - Implement GUI##
##V2.1 - Implement Multiple Screens GUI##
##V3 - Remove all GUI aspects##
##V3.1 - Create initial loop##
##Import Modules##
from forex_python.converter import CurrencyRates
import time
import datetime
import python_weather
import asyncio
##Opening info##
##V3.1##
global enter
enter = 'GO'
while enter == 'GO':
print("========================================================================================================================================================================================")
print("")
print("Welcome to the Traveller Assisstant. This program is able to help you with currency conversions, date and time conversions and viewing weather details of your destination.")
print("")
print("========================================================================================================================================================================================")
time.sleep(2.5)
ori = str(input("Please enter your current country: "))
dest = str(input("Please enter your destination country: "))
time.sleep(5)
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
if check == 'YES':
enter = 'STOP'
elif check == 'NO':
print("Returning to Location Selector")
enter = 'GO'
##V1##
##Change Currency##
#cr = CurrencyRates()
#output = cr.convert(entry1, entry2, entry3)
#final = round(output, 2)
#print("THE FINAL AMOUNT IS:", final, c2)
A simple typo, that's all that was wrong.
In this line of code:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
You are attempting to use the method
.upper()
But your fatal flaw is that you forgot the parentheses.
I changed this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
To this:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
And the code worked perfectly for me
EXPLANATION
In the original code, check could never be equal to 'YES' or 'NO', because of the typo;
.upper was never recognized as a strings' function and returned with this value:
<built-in method upper of str object at 0x105fec130>
.upper() on the other IS in fact a valid function for a string and returned with this value when it was supplied with the input of 'yes':
YES
If you need to exit from the loop when a condition is met you can achieve that easily by using break. So when your condition is met:
either add bellow enter = "STOP" the statement break or just replace enter = "STOP" for break
if check == 'YES':
enter = "STOP"
break
or
if check == 'YES':
break
both should work, I guess you could go with the first answer if you need to keep the state of the variable enter otherwise you could just use the second.
The problem with your original code is that you are missing a parenthesis on the declaration of the upper method in this line:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper
instead it should be:
check = str(input("Are you sure you are in " + ori + ", and would like to go to " + dest + "? ")).upper()
if you don't add the parenthesis to upper() it means you are declaring the object method itself not triggering instead what the method actually does. (In this case making the string uppercase)
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()
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?