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...
Related
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.
This question already has answers here:
Why does adding a trailing comma after an expression create a tuple?
(6 answers)
What is the syntax rule for having trailing commas in tuple definitions?
(10 answers)
Closed 1 year ago.
I was trying to create a new class just today so I can organize pygame code (Learning Pygame/First Project) After making and setting up the class I realized that it had turned all of my parameter type variables into a tuple for no reason. I created a new py file for testing and created to different classes in it with the same everything (however one was copied from my other code the other wasnt) and for some stupid reason the one copied was a tuple and the one made from scratch wasnt. I tested it out some more and found that copying the innit function from the tuple one would result in a tupled variable. I also know that it isn't a part of my IDE due to me testing it in the python console seperate from my IDE and the same issue occured. All I can do now is ask you for your help and provide pictures and my code.
class Person:
def __init__(self, yaxis):
self.yaxis = yaxis
p = Person(64)
print(p.yaxis)
class Player:
def __init__(self, yaxis):
self.yaxis = yaxis,
p1 = Player(64)
print(p1.yaxis)
Output:
p = 64
p1 = (64,)
IDE Image Code Image
Console Code
When you set the yaxis variable in the Player class, you have an extra comma at the end which causes python to automatically convert the variable to a tuple.
This question already has answers here:
Python Tkinter Return
(2 answers)
Closed 8 months ago.
I'm currently working on a GUI project on Python (3.6) using tkinter (8.6).
Following this question I'm wondering how to get back the result of someFunction :
def someFunction(event):
do stuff ..
return(otherStuff)
canvas.bind('<Button-1>',lambda event: someFunction(event))
Thank you in advance :) !
The return values of callback functions like your someFunction are ignored. Rather than using return, have the callback save the value somewhere (in a global variable or an attribute of some kind of object). Or have your function pass the computed value as an argument to some other function that will do something with it.
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)
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.