+ 8
How can I make a variable that it works in functions and out of them ? I want to use it in every were of my code .
19 Antworten
+ 3
Soheil Elahi, in Python you write it in the function, thereby declaring: In this function I want writing-access to x!
+ 6
Soheil Elahi You're actually doing great with asking relevant questions about coding. 👍
+ 4
If you have a variable x in the global space, you can access it in any function by typing:
global x
But you only need it if you want to overwrite the variable: reading access you have automatically!
Also you don't need to globalize lists or dictionaries, since you can use their methods from inside the function.
If you have a list L, you can for example use L.append(your_value)
+ 4
chandrakanth, are you sure you're talking about Python?
+ 4
HonFu At first, I read it the same way as you. However, this is likely a translation issue.
Notice how much the context changes if you simply replace the word "said" with "was talking."
chandrakanth Using the word "said" implies you already explained you were talking about the C language.
However, I think you were simply trying to clarify you were talking about the C language.
I hope this helps clear the air. 😎
+ 4
David Carroll, it doesn't clear the main issue:
If someone asks a question about Python, you shouldn't answer it for C, and especially not without even saying so, since it doesn't contribute anything and may even lead to confusion for OP or other beginners reading the thread.
+ 3
Why are you erasing your comments? This becomes harder to read for other people coming here.
+ 3
HonFu Yes... yes... You're right about that. I was just addressing your response:
"1.) you didn't."
To his attempt at answering your earlier question:
"Are you sure you're talking about Python?"
This certainly doesn't clear the main issue that his original answer is still out of context for this question. 😉
+ 2
Thanks david.
+ 2
Maybe, you can use some like a "sharedPreferences"
+ 2
In python you can write global before it
+ 2
chandrakanth, 1.) you didn't. 2.) Question is about Python.
+ 1
Thanks HonFu.
+ 1
Would this generally be considered bad practice? If you are not careful, you can lose track of whats happening in your program. To pass the variable in, then return it back out, reassigning it wherever its needed, seems much safer.
I dont know. The approach im describing is functional programming, and what youre doing is coding through side effects. But is it pythonic to avoid side effects, or even good practise?
+ 1
no...i said about c language
0
Ok I thought I have written something wrong? Hmmm!
0
Ok
0
u can define that variable as prototype( globally declaration) to access that variable through out the program.
- 3
You have to declare the variable as global and public