Modify a python variable which is inside a loop - python

I have been trying to make a code that requires modification of a variable that is inside a loop.
a = 1
b = 2
while a<b:
print(b)
now I want to change the value of b while the loop is running.
I have tried to find an answer but could not do so.
Can it be possible that I use this loop with an initial value of b and terminate this loop automatically and start a new one when variable b is modified to something else?
How would that be possible?
Note: I want to modify the var b from outside.
Further Explanation:
The code should be designed in such a way that a variable used to check the condition of the while loop can be modified when the loop is already running.
Let's say a user wants to use this while loop as a function, he passes variables in the function to start the loop. Now he wants to change the variable value (in the above case var b), which is used in the while loop condition.
def start_loop(a,b):
while a<b:
#more codes will be included here
print('The loop is running infinitely')
#call the function
start_loop(1,2)
Consol: The loop is running infinitely....
The loop is running infinitely since the loop is already running I can not ask the while loop to change the value of var b.
I am looking for a solution that can handle this situation.
How a user can modify "var b" from outside as the loop is already running?
Or how can I call the same start_loop() function with the modified value of var b? Doing so should result in the termination of the older loop and the start of this new loop.
I hope I'll find the answer here :)
Thanks.

If you want to do what you said at the same time as running the loop, maybe the content of this link will help you pytho.org.
If the solution is published, visit these links: eval(), exec()

Related

Variable value is kept into next iteration of "for" loop?

Take the pseudocode below for example:
Python keeps the previous value for x, so if get_sum() fails, the conditional is still checked using the previous value of x.
Is this because python for loop doesn't introduce a new scope and is it ok to simply del the object at the end of each iteration?
for number in number_list:
try:
x = get_sum()
except:
....
if x > 100:
do something
Every variable in python is created in the scope of their respective functions and classes rather than at different levels of indentation, or in for loops or while loops. There's no block scope in python like there is in java.
If you need x to not retain its old value, you can always set x = None in your except clause and have a conditional catch it later on. If i'm misinterpreting your question please leave a comment

Reuse same variable name twice within a for loop

for i in rates:
if input_currency == currency:
if output_currency in rates[currency]:
pass
else:
for i in rates:
Is it generally a bad thing to use the same variable i again within a for loop? Even if I loop through the same data structure again? PyCharm just tells me it's been used already, but it still works.
It's not wrong. But it's dangerous if you don't know what you are doing. For example, you might have problems if you want to use i inside the outer loop:
rates = [1,2,3,4,5]
for i in rates:
for i in rates:
pass
print(i) # This always prints 5
This may confuse you if you're not familiar with Python. In C, for example, a variable defined inside the inner loop is different from the one that is defined in the outer loop (i.e., you can reuse the same name for different variables).

Do variables created within a function get global scope?

I have a simple function containing a loop that calculates how money grows per year with interest, which got me thinking about scope and variables in Python.
def invest(amount, rate, years):
for i in range(years):
amount = amount + amount*rate
print(f"year {i+1}: ${amount:.2f}")
invest(100, 0.05, 4)
The output:
year 1: $105.00
year 2: $110.25
year 3: $115.76
year 4: $121.55
I know it works, but usually I would create the 'amount' variable above the for loop to ensure that after each iteration, that variable will get updated. Since I didn't do that this time, I assume that this variable gets created globally so that happens automatically.
Are my assumptions correct? Thank you
If it was global then you would be able to access it outside the function. The scope of the variable is limited to that specific function.
You can also create another intermediate variable above the loop but it wouldn't change much about the function- you don't need the original value of amount in your function so for your purposes- using that variable and updating it directly in your loop is fine.
The answer above already satisfy what you asked, but I think the following link might be good for your learning, as it was good for mine. In Python Tutor you can put your code and visualize what happens inside the global scope, functions' scopes, etc. Hope this can help you!

Calling a function within a function creates loop?

I was teaching a python intro course this morning , one of my student came with a question I could not answer
I create a function and within that function, I'm calling the same function and it is looping
def prenom():
print("Nadia")
prenom()
Why?
This is called recursion with no base-case.
You call a function, it (recursively) calls itself and so on. There's no stopping condition, so it will loop forever. This is how infinite loops are created in assembly.
Obviously it will loop.
You haven't set a terminating condition.
Set exit() before calling the function again and you will terminate it successfully (and by termination I mean you will end the program).
Alternatively you may use an if-else condition

Python: break out of for loop calling a function [duplicate]

This question already has answers here:
Break out of a while loop using a function
(3 answers)
Closed 7 years ago.
I need to break out of a for loop according to the result obtained after calling a function. This is an example of what I'm after (does not work obviously):
def break_out(i):
# Some condition
if i > 10:
# This does not work.
return break
for i in range(1000):
# Call function
break_out(i)
Of course this is a very simple MWE, my actual function is much bigger which is why I move it outside of the for loop.
This answer says it is not possible and I should make the function return a boolean and add an if statement inside the for loop to decide.
Since it's a rather old question and it didn't get much attention (also, it's applied to while loops), I'd like to re-check if something like this is possible.
No, it's not (reasonably) possible. You could raise an exception, I suppose, but then you'll have to catch it with a try/except statement outside the loop.
Since OP has expressed curiosity about this, I'm going to explain why Python doesn't allow you to do this. Functions are supposed to be composable elements. They're meant to work in different contexts.
Allowing a function to break out of a loop has two separate problems:
Client code might not expect this behavior.
What if there is no loop?
For (1), if I read some code like this:
import foo # some library I didn't write
while condition:
foo.bar()
assert not condition
I reasonably assume the assertion will not fire. But if foo.bar() was able to break out of the loop, it could.
For (2), perhaps I wrote this somewhere else:
if condition:
foo.bar()
It's not clear what that should do if foo.bar() tries to break out of the loop, since there is no loop.
Rather than return break, return a value that forces a break condition. To extend your example:
def break_out(i):
# Some condition
return i > 10 # Returns `True` if you should break from loop.
for i in range(1000):
# Call function
if break_out(i):
break
# Insert the rest of your code here...

Categories

Resources