Variables defined inside if or for statements [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
What happens to variables assigned for the first time (defined) inside if statement or for loop if long time passed from when their code run. Is there some sort of garbage collection that may result in a not defined variable exception. For example:
if True:
a=1
else:
a=3
# long time passed and other codes run
# .
# .
# .
print (a)
I encountered an error in my code that I suspect this to be the reason. Is it documented somewhere in official Python documentation ?

In Python, if you define a variable within an if statement, it will continue to exist after the if statement concludes. Scopes are defined for a class, a def, or the global scope; if you're in a function and you define a variable inside if, for example, that variable will exist until the function is done executing.
Be careful, however, of defining variables in code like this:
if x == True:
a = 1
else:
print "Not true"
If you have code like this, and x ends up being False, then a will not be defined. Later calls to a will throw an exception as a result. So make sure that you get rid of any potential problems of that sort.

Related

How do I shuffle the print statement of 3 separate functions? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
def a():
print(a)
def b():
print(b)
def c():
print(c)
How do I shuffle a, b and c? I cannot print a,b,c out of the function because there is additional code that I haven't mentioned here in order to simplify the question. I've tried putting all 3 inside random.shuffle() and also tried to associate variables with each function and tried to shuffle the variables (this also doesn't work out because of the code inside each function).
Send help.
The issue you are most likely running into is that you calling the functions inside of your shuffle. Just put the functions themselves without calling them and you can easily do this:
random.shuffle([a,b,c]) # correct
# vs.
random.shuffle([a(),b(),c()]) # incorrect, calls functions before shuffle
Then you can do a for loop and call them or whatever you need:
for f in random.shuffle([a,b,c]):
f()

Should you declare variable before hand in python when using list append and For loop? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
After receiving an error in the code below i ended up adding
new_list = []
summation = 0
after the second line. But i fail to understand why i had to do that. I thought variables did not have to be declared early on in python
a = int(input())
b = int(input())
while a <= b:
if a % 3 == 0:
new_list.append(a)
a += 1
for number in new_list:
summation += int(number)
print(summation / len(new_list))
In general, Python does not require variables to be declared (except for a couple of cases). In this case, you are not declaring a variable but rather initializing it. Let's imagine that variables are boxes. In python, you don't have to say, please make a box and call it x. The issue is when you come across summation += int(number). This tells python, please take out whatever is in the box called summation, add int(number) to it, and put it back in the box. But you haven't yet put anything in the box. So python says sorry, there's nothing in the box at the moment so I can't take anything out. Same for new_list.append(a), that asks python to please append a to whatever is in the box. So python looks in the box to figure out how to append something to it but it can't find anything so it shows an error.
You may ask, why doesn’t python just put 0 in the box? Well, python doesn't know that what you want in the box is an int. Maybe you wanted a fraction, a complex number, or something you make up yourself that happens to be able to be added to a number. The same goes for the list, python does not know that you wanted a list and not a set, dictionary, tuple, counter, queue, or some other collection. So rather than guess, and possibly get it wrong (which would cause all kinds of weird bugs due to the slight differences in how these work with addition), it just gives you an error.
It depends on what you're doing with the variable. If you're assigning a value to the variable, it will initialize the variable in the loop itself. But if you want to modify a variable like you did with .append(), you have to declare it first as it has to be declared to be modified.

Return from function python3 [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I searched the whole internet for the meaning of the return statement.
I know it ends the define statement, but I know it still does something else!
What else does it do?
It returns the flow of control to the calling function. It also returns output/results to the calling function.
Consider the function below:
def am_i_wrong(answer):
if answer == 'yes':
return True
else:
return False
You have multiple returns. So return doesn't simply end the function definition. It instead is the point at which the function returns the result to the caller.
If answer is equal to 'yes' then anything after the if statement (after if and else) is never run because the function has already returned.
The docs explain fully how a return function works. Its also the first answer in the google query python return...

Python not finding array in locals() even though it is there [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making an algorithm that converts numbers into roman numerals, which involves an array. However, when I run my code, I tell it to check if they array exists, and create it if it doesn't (I use this complex method because the code has to restart itself a lot, you will see).
number = input("What number would you like to convert?")
number = int(number)
def alg(n):
if 'roman' in locals():
print("yes")
if n >= 1000:
roman = roman + ["M"]
n = n - 1000
print(roman)
print(n)
#alg(number)
else:
print("end")
else:
print("no")
roman = [""]
print(len(roman))
print(locals())
alg(number)
alg(number)
I have tried researching it on the Python documentation and on this site, but to no avail.
Every invocation of a function has its own set of local variables. Your check will always return false, because you have just entered the function.
If you want to keep the recursive implementation that you currently have, you should pass the roman variable as a second parameter to the alg function.
Are you sure you want to find it in locals() (which will only look in the scope of your function alg which is just starting, thus cannot containing your roman variable) ?
Maybe you want to look up into globals variables with globals() ?
You check for the word 'roman' in locals; this is not going to happen, as you have yet to define roman. A function's locals do not persist from call to call.
Your decrement
n = n - 1000
doesn't do anything useful (yet). The local copy of n gets changed, but you never use it. The original copy (from the main program) is still intact, as integers are not mutable.
Note that your recursive call passes number -- the main program's original number. You're always converting the original, never working on the smaller quantity.
I'll stop here: without design, structure, or comments, this code is a bit hard to follow.

Trying to understand function environments in Python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to understand function environments (global, local). Specifically, I get very confused when there is a nested function that has already been defined globally, for example:
def g(x):
print(x)
def f(f):
f(1)
f(g)
Can someone please help me with this concept? I would greatly appreciate it.
Thanks.
Python uses dictionaries to keep local and global variables in. When looking up a variable reference, it will look into the local dict first. If you want to reference a variable in the global dictionary, put the global keyword in front of it.
Also see answers to this question for more elaborate info.
I agree with user18044, however, is your confusion about the ’f(f)’? I agree that can be really confusing, especially in a non typed language. The argument to ’f’ is a function handle that has a local type scope with name ’f’. The way python decides which ’f’ gets used is explained by 18044. Python looks at the name ’f’ on the function definition and the local parameter ’f’ takes precidence over the global name ’f’ just like would be done if we had a global variable ’dude’ and a local variable ’dude’ in a function. The local overrides the global. Hopes this helps, and makes sense. :-)
The locals for a function consist of everything that was passed in, and every variable that is assigned to and not explicitly tagged as global (or nonlocal in 3.x).
The globals consist of everything that can be seen at global scope, including the function itself.
When a name is referenced, it is looked up in the locals first, and then in the globals if not found in the locals.
When the statement f(g) is run, the statement itself is at global scope, so there are no locals. f and g are both found in the globals: they are both functions. The function defined by def f... is called, with the function defined by def g... being passed as an argument.
When f(f) runs, f is in the locals for the function. It is bound to the passed-in value, which is the function defined by def g.... The body of the function has the statement f(1). 1 is a constant and no lookup is required. f is looked up in the locals, and the passed-in function is found. It - being the function known at global scope as g - is called.
Thus g is, likewise, run with the value 1 bound to the local variable x. That is forwarded to the function print (in 3.x; in 2.x, print is a keyword, so print x is a statement), which prints the value 1.

Categories

Resources