enter image description here
Above code displays output as 10 10 but i used change_counter to update counter value to 11. why is it not updating
Can someone help me plz
The problem is, that you are accessing a static variable.
When you write:
print(demo.counter)
it will always print the number 10, because it is defined this way in the demo-class.
If you want the value to be changed after calling obs.change_counter() you need to access the value of the object "obj" not the class demo.
Another mistake you have made is that you never actually call obj.change_counter, because you forgot the brackets for the function call. The statement obj.change_counter does not throw an error in python but it also wont have any effect.
So instead of this:
obj = demo()
print(demo.counter)
obj.change_counter
print(demo.counter)
You have to do this:
obj = demo()
print(obj.counter) # <- notice the reference to the object
obj.change_counter() # <- notice the brackets
print(obj.counter)
Related
If I make a code like:
lists = ["a='1'", "b='2'", "c=a+b"]
returned_list = []
for x in lists:
exec(x)
print(c)
It works, and It print "12". but, If I use exec() in function:
lists = ["a='1'", "b='2'", "c=a+b"]
def test(lst):
for x in lists:
exec(x)
print(c)
test(lists)
It returns NameError: name 'c' is not defined. How could I use exec() in function?
When you assign a new variable in a function, you are actually assigning a variable in a scope which will be closed after the function is closed.
Imagine it as a bubble with an item inside, which after the bubble blows, the item blows and disappears as well. It means, using exec() in a function would create a temporary local variable. But since functions have a predefined code, adding new variables to them without changing the code directly, would not be possible. in that case we need to use global keyword for each new variable in exec to make the variable save in the main and not in function. Therefor, your list would like this:
lists = ["global a\na='1'"]
also I'm not quite sure if you like the output of a+b be 12, if not, you can just remove the single quotes around each number such as "a=1" to make them integers
for further information check this and this
I have a dataset and I want to make a function that does the .get_dummies() so I can use it in a pipeline for specific columns.
When I run dataset = pd.get_dummies(dataset, columns=['Embarked','Sex'], drop_first=True)
alone it works, as in, when I run df.head() I can still see the dummified columns but when I have a function like this,
def dummies(df):
df = pd.get_dummies(df, columns=['Embarked','Sex'], drop_first=True)
return df
Once I run dummies(dataset) it shows me the dummified columsn in that same cell but when I try to dataset.head() it isn't dummified anymore.
What am I doing wrong?
thanks.
You should assign the result of the function to df, call the function like:
dataset=dummies(dataset)
function inside them have their own independent namespace for variable defined there either in the signature or inside
for example
a = 0
def fun(a):
a=23
return a
fun(a)
print("a is",a) #a is 0
here you might think that a will have the value 23 at the end, but that is not the case because the a inside of fun is not the same a outside, when you call fun(a) what happens is that you pass into the function a reference to the real object that is somewhere in memory so the a inside will have the same reference and thus the same value.
With a=23 you're changing what this a points to, which in this example is 23.
And with fun(a) the function itself return a value, but without this being saved somewhere that result get lost.
To update the variable outside you need to reassigned to the result of the function
a = 0
def fun(a):
a=23
return a
a = fun(a)
print("a is",a) #a is 23
which in your case it would be dataset=dummies(dataset)
If you want that your function make changes in-place to the object it receive, you can't use =, you need to use something that the object itself provide to allow modifications in place, for example
this would not work
a = []
def fun2(a):
a=[23]
return a
fun2(a)
print("a is",a) #a is []
but this would
a = []
def fun2(a):
a.append(23)
return a
fun2(a)
print("a is",a) #a is [23]
because we are using a in-place modification method that the object provided, in this example that would be the append method form list
But such modification in place can result in unforeseen result, specially if the object being modify is shared between processes, so I rather recomend the previous approach
i tried calling .copy on it and then passing it in the function. that didn't work.
when i tried coppying in the function itself it still changed the original list.
the function is in another file
main.py
win_condition.check_r_win(board)
win_condition.py
def check_r_win(board):
board = _board.copy()
for col in board:
while(len(col) <= ROWS):
col.append("-")
I don't really get what you are trying here. Python's list is a mutable object type. If you pass a object reference of a list to a function and change the list within this function, it also gets changed outside of the function scope.
How can I access a list element using the name of the list?
I would like to allow a user to edit the code in determine a single variable to be inputted into a function. For example:
blah = [1,2]
blah2 = 5
toBeChanged = "blah2"
def foo():
print(blah)
def changeVariable():
globals()[toBeChanged] += 1
for time in range(5):
changeVariable()
simulate
This works for blah2 since it is a simple variable, however it will not work for blah[0] since it is part of a list. I've also tried placing my variables into a dictionary as other answers have suggested, but I still am unable to change list elements through a simple string.
Is there a way to do this that I am missing? Thanks!
Rather than using globals() and altering directly it would be much, much better to use a dictionary to store the variables you want the user to alter, and then manipulate that:
my_variables = {
'blah': [1,2]
'blah2': 5
}
toBeChanged = "blah2"
def foo():
print(my_variables['blah'])
def changeVariable():
my_variables[toBeChanged] = my_variables.get(toBeChanged,0) + 1
for time in range(5):
changeVariable()
This has the added advantage that if a user enters a variable that doesn't exist a default is chosen, and doesn't override any variables that might be important for future execution.
(background first: I am NEW to programming and currently in my very first "intro to programming class" in my college. This is our second assignment dealing with Functions. So far functions have been a pain in the ass for me because they don't really make any sense. ex: you can use miles_gas(gas) but then don't use "miles_gas" anywhere else, but the program still runs??, anyways)
Okay, I've looked EVERYWHERE online for this and can't find an answer. Everything is using "Exceptions" and "try" and all that advanced stuff. I'm NEW so I have no idea what exceptions are, or try, nor do I care to use them considering my teacher hasn't assigned anything like that yet.
My project is to make a program that gives you the assessment value, and the property tax upon entering your property price. Here is the code I came up with (following the video from my class, as well as in the book)
ASSESSMENT_VALUE = .60
TAX = 0.64
def main():
price = float(input('Enter the property value: '))
show_value(value)
show_tax(tax)
def show_value():
value = price * ASSESSMENT_VALUE
print('Your properties assessment value is $', \
format(value, ',.2f'), \
sep='')
def show_tax(value,TAX):
tax = value * TAX
print('Your property tax will be $', \
format(tax, ',.2f'), \
sep='')
main()
Upon running it, I get it to ask "blah blah enter price:" so I enter price then I get a huge red error saying
Traceback (most recent call last):
File "C:/Users/Gret/Desktop/chapter3/exercise6.py", line 41, in <module>
main()
File "C:/Users/Gret/Desktop/chapter3/exercise6.py", line 24, in main
show_value(value)
NameError: name 'value' is not defined
But I DID define 'value'... so why is it giving me an error??
Python is lexically scoped. A variable defined in a function isn't visible outside the function. You need to return values from functions and assign them to variables in the scopes where you want to use the values. In your case, value is local to show_value.
When you define a function, it needs parameters to take in. You pass those parameters in the brackets of the function, and when you define your function, you name those parameters for the function. I'll show you an example momentarily.
Basically what's happened is you've passed the function a parameter when you call it, but in your definition you don't have one there, so it doesn't know what to do with it.
Change this line:
def show_value():
To this line:
def show_value(price):
And show_value to show_value(price)
For example:
In this type of error:
def addition(a,b):
c = a + b
return c
addition() # you're calling the function,
# but not telling it the values of a and b
With your error:
def addition():
c = a + b
return c
addition(1,2) # you're giving it values, but it
# has no idea to give those to a and b
The thing about functions, is that those variable only exist in the function, and also the name of the parameters doesn't matter, only the order. I understand that's frustrating, but if you carry on programming with a more open mind about it, I guarantee you'll appreciate it. If you want to keep those values, you just need to return them at the end. You can return multiple variables by writing return c, a, b and writing the call like this sum, number1, number2 = addition(1,2)
Another problem is that I could call my addition function like this:
b = 1
a = 2
addition(b,a)
and now inside the function, a = 1 and b = 2, because it's not about the variable names, it's about the order I passed them to the function in.
You also don't need to pass TAX into show_tax because TAX is already a global variable. It was defined outside a function so it can be used anywhere. Additionally, you don't want to pass tax to show_tax, you want to pass value to it. But because show_value hasn't returned value, you've lost it. So return value in show value to a variable like so value = show_value(price).