+ 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

18th Nov 2020, 4:06 AM
Hafizhul Qisthi M
Hafizhul Qisthi M - avatar
9 Respuestas
+ 5
Your function doesn't return anything. Add a last line 'return sum_now'.
18th Nov 2020, 4:13 AM
David Ashton
David Ashton - avatar
+ 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
18th Nov 2020, 11:19 AM
Coder
Coder - avatar
+ 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)
18th Nov 2020, 4:28 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 2
Make sure from the characteres of the variable's word as python is case sensitive and i will try to run your code
18th Nov 2020, 4:14 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 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
18th Nov 2020, 4:21 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 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
18th Nov 2020, 4:31 AM
Muhammad Galhoum
Muhammad Galhoum - avatar
+ 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
18th Nov 2020, 4:26 AM
Hafizhul Qisthi M
Hafizhul Qisthi M - avatar
+ 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.
18th Nov 2020, 4:33 AM
Hafizhul Qisthi M
Hafizhul Qisthi M - avatar
+ 1
i like turtles
18th Nov 2020, 4:38 PM
Otto Stober