Can't call a previously declared dictionary though a method - python-3.x

I'm fairly new to python...aka just started.
So i was making a simple game and i'm trying to get a dictionary to work through out a claas and cant get it to work.
class Map(object):
def __init__(self):
self.Eng = {
"1": "Map_Eng()",
"2": "Guard_Fight()",
"3": "Item_Eng()"
}
def enter_room(self):
pass
def exit_room(self):
print("You move onto the next room.")
return self.Eng[1]

The problem is small. Your dictionary has an entry with key "1" (a string), but not with key 1 (a number). To fix your problem, change the line
return self.Eng[1]
to
return self.Eng["1"]

Related

Access method from different package in Python

I am trying to automate android game. I have so many methods so I break my code in 3 parts.
main, functions and collectors.
I have a method in functions which is:
def search_image(image, confidence=.6, click=True):
location = pyautogui.locateCenterOnScreen(image, confidence=confidence)
if location is not None:
if click:
pyautogui.click(location)
return location
else:
return False
But I cant access it in collectors, like this:
from functions import*
def collect_product():
if search_image(r'Resources\NewOrderAvailable.png') is not False:
search_image(r'Resources\NewOrderAvailable2.png')
for item in range(0, 6):
search_image(r'Resources\Collect.png', confidence=.8)
search_image(r'Resources\Back.png')
search_image(r'Resources\CloseOrderMenu.png')
else:
return False
I got NameError: name 'search_image' is not defined. I need to duplicate that method to make it work. I was wondering what went wrong and how to fix it?
Your function is not an instance of the class. You need to add a self keyword to make it accessible outside.
def search_image(self, image, confidence=.6, click=True):
location = pyautogui.locateCenterOnScreen(image, confidence=confidence)
if location is not None:
if click:
pyautogui.click(location)
return location
else:
return False
Try
import functions
functions.search_image('...')

I am new to python coding and i do not understand how to use a variable from another method

Here is what i have tried:
I do not understand how can i use a variable from another method of same class. Also please explain how can i use a variable from a method in different class. I tried searching but could not find a solution. So what i did to pass the test cases is to copy code from calculate_percentage and paste it in find_grade method. It worked but i think this is the worst method. So please tell a possible solution.
Thanks
#!/bin/python3
#Enter your code here. Read input from STDIN. Print output to STDOUT
class Student:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
length=len(self.marks_list)
sum=0
for i in self.marks_list:
sum+=i
percent=sum/length
return int(percent)
def find_grade(self,percent):
if percent>=80:
return 'A'
elif percent>=60 and percent<80:
return 'B'
elif percent>=40 and percent<60:
return 'C'
elif percent<40:
return 'F'
if __name__ == '__main__':
roll=int(input())
name=input()
count=int(input())
marks=[]
for i in range(count):
marks.append(int(input()))
s=Student(roll,name,marks)
print(s.calculate_percentage())
print(s.find_grade())
i am getting the error:
print(s.find_grade())
TypeError: find_grade() missing 1 required positional argument: 'percent'
Thanks for every one who answered but i found the answer:
i just need to put self.percent
or percent=self.calculate_percentage() to call the method and use the variables
The assumption would be that the marks are x/100 scale while otherwise your percentage will be incorrect.
As said above, you need to pass the variable percent back to the function since it is not known in the class, it is only returned.
print(s.find_grade(s.calculate_percentage()))
or if the percentage is a class variable you can rewrite it into the class like this:
from statistics import mean
class Student2:
def __init__(self,roll,name,marks_list):
self.roll=roll
self.name=name
self.marks_list=marks_list
def calculate_percentage(self):
self.percent=mean(marks)
return int(self.percent)
def find_grade(self):
if self.percent>=80:
return 'A'
elif self.percent>=60 and self.percent<80:
return 'B'
elif self.percent>=40 and self.percent<60:
return 'C'
elif self.percent<40:
return 'F'
percent = int(0)
# test variables
vRoll = 2
vName = 'student'
vCount= 2
vMarks= [100, 75]
# main
if __name__ == '__main__':
roll=vRoll
name=vName
count=vCount
marks=vMarks
s2=Student2(roll,name,marks)
print(s2.calculate_percentage()) # 87
print(s2.find_grade()) # A

Cannot pass updated list in recursion function

I have a homework problem which requires me to check if a dictionary value is also a key word, and continue calling values until I find one that is not also a key. The trick is, you can get stuck on a never ending loop.
I tried to remedy this by tracking which values have previously been used in order to be able to kick out of recursion, but the homework problems auto grader does not allow this.
Here is my code:
def rabbit_hole(my_dict, string, new_list = []):
if string in new_list:
return False
try:
new_list.append(string)
value = my_dict[string]
return rabbit_hole(my_dict, value, new_list)
except:
return string
d = {"bat": "pig", "pig": "cat", "cat": "dog", "dog": "ant",
"cow": "bee", "bee": "elk", "elk": "fly", "ewe": "cod",
"cod": "hen", "hog": "fox", "fox": "jay", "jay": "doe",
"rat": "ram", "ram": "rat"}
In the example above, if we execute...
print(rabbit_hole(d, "rat"))
... this shows an example of a never ending loop and I would like it to return False. Is there an obvious reason this doesn't work with the auto grader? Or is there another way to track which keys have already been used?
It could be that your grader is checking for additional arguments to the function and doesn't allow for any.
How about just deleting the dictionary entry you've already checked?
def rabbit_hole(my_dict, string):
try:
value = my_dict[string]
my_dict.pop(string, None)
return rabbit_hole(my_dict, value)
except:
return string

How to edit strings in a list

What I want is this - I have a list of names created from user input. now i have to come up with a way for the user to edit a name by entering the name that they what to edit and then obviously edit it into what they want and store it in the list.
if it helps heres everything I have so far. def edit() is where im struggling.
def mainMenu():
print("\nMAIN MENU")
print("1. Display Members:")
print("2. Add A Member(s):")
print("3. Remove A Member:")
print("4. Edit Member:")
print("5. Exit:")
selection = int(input("\nEnter Choice: "))
if selection == 1:
display()
elif selection == 2:
add()
elif selection == 3:
remove()
elif selection == 4:
edit()
elif selection == 5:
exit()
else:
print("Invalid choice, enter 1-5.")
mainMenu()
def display():
#displaying roster...
print(roster)
mainMenu()
def add():
#adding team members...
size = int(input("How many players are you adding?"))
global roster
roster = [0] * size
for i in range(size):
roster[i] = input("Enter members name: ")
roster.append(roster)
mainMenu()
def remove():
#removing a team member...
roster.remove(input("Enter member to be removed: "))
mainMenu()
def edit():
#edit a team member...
roster.insert(input("Enter Name to be edited: "))
mainMenu()
mainMenu()
Removing and adding elements are pretty easy in python because they are directly supported by the language. Each of them can be translated into only one instruction.
When something doesn't seem very obvious, such as the editing functionality you are trying to implement, try breaking it down to things that can be expressed as a simple operation that holds one one line (even if not in order).
To find the answer I thought this: somewhere in my code, I want to type roster[ind_name_to_edit] = new_name.
I knew then that before typing this, I would want to find the value of ind_name_to_edit. This can be done by roster.index(name_to_edit). And you already know how to get the name to be edited and the name to edit ;)
If you're still unsure how to do what you want to do, re-read this answer and see the documentation of the index method of list in python3 and maybe some examples here.
N.B: If your list is supposed to be sorted in some way, you should implement your own search algorithm instead of using index, and you should consider re-sorting the list after the edit. I know it's a long shot but just in case.

Is there a nice(r) way to have default values in objects

What I'm aiming at is having a object in python3 behaving as normal with regards to attribute access, except that if an attribute is not available through the normal lookup it should fetch/calculate the value in some other way.
I know that one could solve the problem by defining the __getattr__ method:
def __getattr__(self, key):
if key == 'foo':
return calculate_default_foo()
elif key == 'bar':
return getattr(dfltobj, 'bar')
elif key == 'frob':
return 42
raise AttributeError
but that feels so python2 so I wonder if there's a more elegant way to do this in python3. Just defining propertys don't work that well since they completely override accesses to that attribute, but otherwise that would be a nice approach if it had worked.
I don't think there's a way around it, but there is a nice(r) way of modifying __getattr__:
def __getattr__(self, item):
if item == "foo" and not self.foo:
return calculate_default()
return self.__getattribute__(foo)
Hope it helped :)

Resources