Turning a string into variable or object, Python [duplicate] - python

This question already has answers here:
How to give column name dynamically from string variable in sql alchemy filter?
(4 answers)
Closed 5 years ago.
I've had this problem in the past and never found the solution. I've checked ton's of google links and still don't know.
What I want to do is use a string as a variable. I'm working with SQLalchemy so will use the example straight from my project: (look for the variable 'objective' in the function)
Here's an example:
def win_ratio_p_obj(objective):
#want to find the win/loss ratio for each obj_first, ie. 60% of times when team gets fblood you also win vs. 40% of time you lose
obj_totals = session.query(Match.win, func.count(Match.win)).filter(Match.**objective** == 't').group_by(Match.win).order_by(Match.win).all()
win_chance = obj_totals[1][1]/(obj_totals[0][1]+obj_totals[1][1])
return win_chance
objective = 'first_dragon'
x = win_ratio_p_obj(objective)
objective = 'first_blood'
y = win_ratio_p_obj(objective)
objective = 'first_turret'
z = win_ratio_p_obj(objective)
objective = 'first_inhib'
Returns:
Traceback (most recent call last):
Python Shell, prompt 15, line 1
builtins.AttributeError: type object 'Match' has no attribute 'objective'
So what I want to do is use each objective as a variable name with the aim of reducing code repetition. I know I could very easily copy paste the function a few times but that seems silly.
At the moment the code above won't recognise the objective variables values as variables instead of strings.
Any answers will be super well appreciated!

It seems like you could use getattr:
getattr(Match, objective)

Related

Why do we use return? (python) what scenarios would it be useful in? [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
This is a program to make the text print with each word beginning with a capital letter no matter how the input is.
So my question is why do we use return here :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
return f"{formatted_f_name}{formatted_l_name}"
print(format_name("ABcDeF", "Xy"))
when I could just do this :
def format_name(f_name, l_name):
formatted_f_name = f_name.title()
formatted_l_name = l_name.title()
print(f"{formatted_f_name}{formatted_l_name}")
format_name("ABcDeF", "Xy")
What scenarios would it be really useful in?
The main reason that the return keyword is used is so that the value of the function can be stored for later, rather than just printing it out and losing it.
e.g.
def someFunction(a,b):
return(a+b/3)
a=someFunction(1,2)
This means that what the function does can be stored for later.
For example:
print(a)
print(a/2)
print(a+3)
return statements don't just replace print, they allow you to do a load of other things by storing the end value (the value inside return) in a variable.
print()ing in a function, however, only allows us to print the variable to the console, not allowing us to do anything or use the value that it prints.
e.g.
def someFunction(a,b):
print(a+b/3)
a=someFunction(1,2)
print(a)
Although the function already prints the value off for you, the variable I assigned it to shows that the function is practically useless unless you run it a bunch of times. a will print off None in the case above.
Hope that was helpful.

PyCharm - Shadows name from outer scope [duplicate]

This question already has answers here:
Shadows name xyz from outer scope
(5 answers)
What is the problem with shadowing names defined in outer scopes?
(10 answers)
Closed 1 year ago.
I am learning Python and am trying to take concepts that I learn from video tutorials and add to them. I just watched a video on If Statements and Comparisons, and I wanted to add to what was done in the video by getting input from the user. I received the "shadows name 'ans' from outer scope" warning and have seen others ask this question on the site, but their examples do not involve getting input from the user. Thank you in advance for your help!
ans = input("What color is the sky? ")
def color(ans):
if ans == str("Blue"):
return str("Correct!")
else:
return str("Incorrect.")
print(color(ans))
First things first - the warning is specific to pycharm and your code should run correctly as it is.
Now, there are two ways how you can get rid of the warning:
Either you can rename the argument used within the function i.e. instead of giving it same name ans, you can opt for a different name e.g. answer.
The other way could be suppress this warning in pycharm:
# noinspection PyShadowingNames
def color(ans):
# rest of the code...

print(function) vs print(function()) in Python [duplicate]

This question already has answers here:
What is the difference between calling function with parentheses and without in python? [duplicate]
(5 answers)
Closed 2 years ago.
I've got following simple script, which gets text from some site:
from urllib.request import urlopen
def fetch_words():
contentdownload = urlopen('https://wolnelektury.pl/media/book/txt/treny-tren-viii.txt')
decluttered = []
for line in contentdownload:
decltr_line = line.decode('utf8').split(" ")
for word in decltr_line:
decluttered.append(word)
contentdownload.close()
return decluttered
When adding: print(fetch_words) at the end, the program returns: <function fetch_words at 0x7fa440feb200>, but on the other hand, when I replace it with: print(fetch_words()) it returns the content of the website, that a function downloads.
I have following question: why it works like this, what's the difference: function with () or without...
All help appreciated!
When you call print(fetch_words) you get the representation of the function as an object.
def fetch_words():
pass
isinstance(fetch_words,object)
return True. Indeed, functions in Python are objects.
So when you type print(fetch_words) you actually get the result of fetch_words.__str__(), a special method which is called when you print object.
And when you type print(fetch_words()) you get the result of the function (the value the function returns). Because, the () execute the function
So fetch_words is an object and fetch_words() execute the function and its value is the value the function returns.

Python Class shows name not defined [duplicate]

This question already has answers here:
Python - Why is this class variable not defined in the method?
(3 answers)
Why is instance variable not getting recognized
(2 answers)
Closed 6 years ago.
I am writing a piece of code for a homework class, which should allow me to calculate various distance statistics about two lists. However, when I assign the lists to the class, and try to print the result of one of the functions, I get the error,
NameError: name 'ratings1' is not defined
Leading me to believe that I did something incorrectly either in my __init__ function or the referencing in the functions. Can you help clarify what I'm doing wrong?
class similarity:
def __init__(self, ratingX, ratingY):
self.ratings1=ratingX
self.ratings2=ratingY
def minkowski(self,r):
self.r=r
mink=0
length=len(ratings1)
for i in range(0,length):
mink=mink+(abs(ratings1[i]-ratings2[i]))**r
mink=mink**(1/r)
result='Given r=%d, Minkowski distance=%f'%(r,mink)
return result
def pearson(self):
Xavg=average(ratings1)
Yavg=average(ratings2)
n=len(ratings1)
diffX=[]
diffY=[]
for i in range(0,n):
diffX.append(ratings1[i]-Xavg)
diffY.append(ratings2[i]-Yavg)
return diffX
diffXY=[]
for i in range(0,n):
diffXY.append(diffX[i]*diffY[i])
example2=similarity([1,3,5,5,6],[4,6,10,12,13])
print(example2.pearson())
Note: this error persists if I change the references to "ratings1/2" to "ratingsX/Y" in the functions.
You need to use self before every reference to instance variable, ie self.ratings1, and your indentation is wrong as well.
ratings are associated with class. Use self.ratings1 and so on..
I just figured out my mistake. For each function I failed to use the self. phrase before the ratings name. To amend this, I added
ratings1=self.
ratings2=self.ratings2
To the beginning of each function. Problem solved.

Python - Function - Argument said to be "undefined"

I'm currently taking a Python course, and got to the chapter in our book that talks about functions. (Please note, this is my first time learning any programming.)
One of the exercises I'm working on at the moment asks for me to turn a bunch of conditional statements into a function (i.e. generalization).
To make this brief, my problem is this:
After I define a function, let's say like so...
def count_letter(letter,string):
count = 0
for letter in string:
count += 1
print(count)
(That is the work, as far as I can recall, for what I typed up for the problem.)
I run the program, then call the function in the shell as usual...
(Example directly below)
>>> count_letter(a,bananana)
And I get the following output...
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
count_letter(a,bananana)
NameError: name 'a' is not defined
My teacher and everyone in our class can't figure out why we're getting such an error. We would understand if it was some other type of an error, but having the shell tell us an argument is 'undefined' (i.e. a variable, as we understand the error) is something we haven't been able to figure out.
We've been staring at the code for a week and still can't figure it out.
Any help would be very appreciated.
Afterthought: I'm trying to count the number of "a"s within "bananana" in the example. Thought I should clear the ambiguity there.
As written, a and bananana are the names of variables which should be defined in a similar way you defined the variable count. For example:
>>> character_to_search = 'l'
>>> text = 'Hello World'
>>> count_letter(character_to_search, text)
would be a correct syntax, because both character_to_search and text are undefined.
Another possibility is that instead of using actual variables, your intention was to pass strings directly to the function. In this case, your syntax is slightly incorrect. It should be (note the single quotes):
count_letter('a', 'bananana')

Categories

Resources