0

How to use a variable's value from 1 method to another method?

def sum(): a =2 b=5 s= a+b return s def add(): c=5 print(s+c) add() This show error: s not defined.. How can use 's' value in my add() method?(without using global)

5th Nov 2019, 2:51 AM
Amit Dubey
Amit Dubey - avatar
7 ответов
+ 4
I am a little confused about this code. May be this is a snippet of a more complete code? For this situation now: if you just call add(), s is not existing at all, because it's only created if the function sum() is called. But if you call sum() like this: s = sum() *s* is available because sum returns the content of s. So you can do: def sum(): a =2 b=5 s= a+b return s def add(): c=5 print(s+c) s = sum() add() # output : 12
5th Nov 2019, 10:41 AM
Lothar
Lothar - avatar
+ 2
Just write in the add function: s = sum()
5th Nov 2019, 4:31 AM
Enzo Falcon
Enzo Falcon - avatar
0
Use `global s`.
5th Nov 2019, 3:08 AM
o.gak
o.gak - avatar
0
o.gak without using global..i forgot to write it in the description..
5th Nov 2019, 3:10 AM
Amit Dubey
Amit Dubey - avatar
0
You must first call sum function. So "s" will be defined and then you can call add.
5th Nov 2019, 3:34 AM
Qasem
0
Amit Dubey As I know, `global` is used for this case. But you say "without". This is out of my knowledge... And what do you do this for? for what case? Also, without sending a parameter?
5th Nov 2019, 3:51 AM
o.gak
o.gak - avatar
0
Thanks everyone for the help!
6th Nov 2019, 3:41 AM
Amit Dubey
Amit Dubey - avatar