+ 2
can't define variable in def function
hallo, i have problem with def function. i have simple code, but it doesn't work because one variable is not defined. Here is code: def discount(percent): sum_now = int(sum - (sum * (percent / 100))) sum = 300 if sum >= 300: discount(10) money = 300 if money >= sum_now: refund = money - sum_now print("refund is: ", refund) #output when running is: if money >= sum_now: NameError: name 'sum_now' is not defined Process finished with exit code 1
9 Réponses
+ 5
Your function doesn't return anything. Add a last line 'return sum_now'.
+ 4
You defined a varible inside a function that cannot be accessed through outside the function
So you need a global variable
Or you can can return sum_now at the end of the line then store it in the varible and use as you need
+ 3
Show this code
def discount(percent):
sum_now = int(input(sum - (sum * (percent / 100))))
money = 300
if money >= sum_now:
refund = money - sum_now
print("refund is: ", refund)
sum = 300
if sum >= 300:
discount(10)
+ 2
Make sure from the characteres of the variable's word as python is case sensitive and i will try to run your code
+ 2
First:U forgot the input function inside the int function
Second: u can not call the variable sum_now outside the function as it is a private variable
+ 2
I can help u more if u told me what is the problem that u write this code for it
I put my code in the previous comment the out put is 270.0 with out any wrong
+ 1
but if i define 'sum_now' outside from func like example 'sum_now = 0', the value will be 0. I want show the value from 'sum_now' based on the results of calculations in that function, is '270' after calculating
+ 1
ok thanks for helping . so the conclusion is We only give commands to the function outside, where the function in the room has already provided all the calculations to be calculated along with the output what we want to show.
+ 1
i like turtles