This is probably a dumb question, but I'm new to programming and I have a recursive function set up that I'm trying to figure out. For any print function in Python, is it necessarily true that lines are printed in the order that they are written in the script OR for larger outputs, is it possible that smaller length outputs can get printed first in the console even though the print statement is later in the code (maybe due to some memory lag)?
Example:
def test_print():
#don't run this, but was meant for scale. Is there any chance the 1 would print before the list of lists?
print([[i for i in range(10000)] for j in range(10000)])
print(1)
Print statements pile output into stdout in the order the code was written. Top to bottom. It isn't possible any other way because that's the way the code is interpreted. Memory lag doesn't play any role here because the output to your console is a line for line rendition of the data that was piled into stdout. And the order the data was written to it can't change, so you'll maintain chronology. Of course, you can always play around with the how the print function itself works. But I wouldn't recommend tampering with standard library functions.
As said above, print() function is executed in the order which they are in your code. But you yourself can change the order in which you want it executed, after all you have every right to instruct the code to do whatever you want.
You'll always get the same order in the output as the order you execute print() functions in Python.
Related
I am working on a problem where i should collect data from running program numerous times. For example, every time the program finishes commands, it give certain value t, which is different every time run it. My task is to collect t from N runs of the program. t is going to be different every run. here is the program:
import random
th=0
t=0
tr=0
result=[]
for i in range(7):
i=random.randint(0,1)
result.append(i)
print(result)
a=0
b=len(result)-1
while th<50:
j=random.randint(a,b)
i=j-1
k=j+1
if k<b
k=0
if result[i]==result[k]:
if result[j]!=result[i]:
result[j]==result[i]
th=0
t+=1
else:
th+=1
t+=1
else:
th+=1
t+=1
tr= t-th
print(tr)
print (result)
In this program every run gives you new result. In this generated array there will be obviously every time different arrangement of 0 and 1 and therefore, different t. So resulting t, tr, will be ofcourse different.
I don't know wheter i should do it in new window, or there is a certain function that can do this. Also, if this question is to easy, and there is literature for it, please write what is the name of this kind of problem. thanks :)
btw, im working in python 3.6
See how to make one Python script launch another: you can write a Python script to run the other script and gather the output. You can receive the output as return value from a function call, and tally it just as you would from any function.
Note that your "running program" and your master script need to agree on the form of the information returned: know the data types you're receiving. If you're in doubt, start by having your master script print out what it receives, and the type of each returned value.
display expression: prints out the value of an expression each time it gets changed. This is useful for monitoring the value of variables that get changed in loops. So, suppose the following is the code:
for i in range(100):
for j in range(100):
a=f(i,j)
I know something is wrong with the execution of a=f(i,j) for certain values of i and j. Then, how to use the display command from pdb module to find out the values of i and j when it does not work? I suppose when you use display command, it will display the value of i and j automatically, right? Do I need to combine the c command and b command from pdb module also? Many thanks for your time and attention.
display sets a "watch", so that each time execution stops (whether by completing a next, a step, or an until, or breaking on a continue ), if the value has changed, it will print a message showing the old value and the new value.
Since you know something is wrong with your f function, your easiest solution is to put a break on that function, and set display of the inputs inside that scope. Since you have shown us nothing about f, I don't know what the input variables will be called at that level, but it's likely that it won't be "i" and "j", so set the display appropriately.
I find display most useful for when I'm stepping through code that involves loops, using n or s or c. It keeps track of variables for me, and saves me from having to print the variables I'm interested in. If you know your problem is in f, you'll have to step through the code there yourself, and check all the variables at all the interesting statements. If you find yourself checking a variable repeatedly, that's where you use display.
I'm integrating MicroPython into a microcontroller and I want to add a debug step-by-step execution mode to my product (via a connection to a PC).
Thankfully, MicroPython includes a REPL aka Python shell functionality: I can feed it one line at a time and execute.
I want to use this feature to single-step on the PC-side and send in the lines in the Python script one-by-one.
Is there ANY difference, besides possibly timing, between running a Python script one line at a time vs python my_script.py?
Passing one line of code at a time on stdin is a completely unacceptable alternative to a proper debugger.
Let's say that you want to debug the following:
def foo(): # 1
for i in range(10): # 2
if i == 5: # 3
raise Exception("Argh!") # 4
# 5
foo() # 6
...in a proper step-by-step debugger, the user could use it like so:
break 4
run
Now, how are you going to do that? If you enter the function in a REPL, the function is defined as one operation, and it runs as one operation. It doesn't stop at line 6. It doesn't let you proceed line-by-line. The same is true of the for loop: Entering the text of the for loop one line at a time doesn't let you step it before the exception is thrown.
If you eliminate the function, and eliminate the loop (generating the code _something = iter(range(10)); i=_something.next(), maybe?), then you need to emulate the effects of scoping. It means you have a hugely different language than the one you're purportedly "debugging".
I don't know whether MicroPython has compile() and exec() built-in.
But when embeded Python has them and when MCU has enough RAM, then I do the following:
Send a line to embeded shell to start a creation of variable with multiline string.
'_code = """\'
Send the code I wish executed (line by line or however)
Close the multiline string with """
Send exec command to run the transfered code stored in the variable on MCU and pick up the output.
If your RAM is small and you cannot transfer whole code at once, you should transfer it in blocks that would be executed. Like functions, loops, etc.
If you can compile bytecode for MicroPython on a PC, then you should be able to transfer it and prepare it for execution. This would use a lot less of RAM.
But whether you can inject the raw bytecode into shell and run it depends on how much MicroPython resembles CPython.
And yep, there are differences. As explained in another answer line by line execution can be tricky. So blocks of code is your best bet.
Is there ANY difference ...
Yes.
The code below, for example, works in .py file, but is a SyntaxError in the interactive interpreter:
x = 1
if x == 1:
pass
x = 2
There are many other differences, but this alone should be enough to scare you away from the idea.
This code has me lost. When run, it outputs sequences which I finds strange:
def print_n(number):
if (number <= 0):
return None
else:
print number
print_n(number-1)
print_n(number-1)
print_n(4)
I thought it would output this sequence:
4,3,2,1,1,2,1,3,2,1
however it actually outputs:
4,3,2,1,1,2,1,1,3,2,1,1,2,1,1
I tried to draw the stack diagram of this function but when I get lost at the second appearance of the print_n(number-1).
I can understand this program without the second appearance of the print_n(number-1), as it's just normal recursion. However, the second print_n(number-1), seems much more complicated than I expected, I don't know how to trace this function call and explain the result...
Since the if block has an unconditional return, you can remove the else and the program will continue to behave the same way.
def print_n(number):
if (number <= 0):
return None
print number
print_n(number-1)
print_n(number-1)
Here, it's more apparent what is going on: You print number, and then call print_n twice using number-1. You can work backwards to derive the output.
print_n(1) prints "1"
print_n(2) prints "2" plus "1" plus "1": "211"
print_n(3) prints "3" plus "211" plus "211": "3211211"
print_n(4) prints "4" plus "3211211" plus "3211211": "432112113211211"
I liked the answer of Kevin, but let me add a few words towards "understanding recursion":
I often suggest using sheets of paper representing the stack. each sheet contains its local varaibles and current state - and you can mark the line you are "processing" with a pen.
Use a separate sheet as output / console.
This gives you a very good understanding of what is going on.
Of course, following your code in a debugger and examining the stack trace can be helpful as well. But try the paper-approach first!
I have got stuck with a problem.
It goes like this,
A function returns a single result normally. What I want is it to return continuous streams of result for a certain time frame(optional).
Is it feasible for a function to repeatedly return results for a single function call?
While browsing through the net I did come across gevent and threading. Will it work if so any heads up how to solve it?
I just need to call the function carry out the work and return results immediately after every task is completed.
Why you need this is not specified in the question, so it is hard to know what you need, but I will give you a general idea, and code too.
You could return in that way: return var1, var2, var3 (but that's not what you need I think)
You have multiple options: either blocking or non-blocking. Blocking means your code will no longer execute while you are calling the function. Non-blocking means that it will run in parallel. You should also know that you will definitely need to modify the code calling that function.
That's if you want it in a thread (non-blocking):
def your_function(callback):
# This is a function defined inside of it, just for convenience, it can be any function.
def what_it_is_doing(callback):
import time
total = 0
while True:
time.sleep(1)
total += 1
# Here it is a callback function, but if you are using a
# GUI application (not only) for example (wx, Qt, GTK, ...) they usually have
# events/signals, you should be using this system.
callback(time_spent=total)
import thread
thread.start_new_thread(what_it_is_doing, tuple(callback))
# The way you would use it:
def what_I_want_to_do_with_each_bit_of_result(time_spent):
print "Time is:", time_spent
your_function(what_I_want_to_do_with_each_bit_of_result)
# Continue your code normally
The other option (blocking) involves a special kind of functions generators which are technically treated as iterators. So you define it as a function and acts as an iterator. That's an example, using the same dummy function than the other one:
def my_generator():
import time
total = 0
while True:
time.sleep(1)
total += 1
yield total
# And here's how you use it:
# You need it to be in a loop !!
for time_spent in my_generator():
print "Time spent is:", time_spent
# Or, you could use it that way, and call .next() manually:
my_gen = my_generator()
# When you need something from it:
time_spent = my_gen.next()
Note that in the second example, the code would make no sense because it is not really called at 1 second intervals, because there's the other code running each time it yields something or .next is called, and that may take time. But I hope you got the point.
Again, it depends on what you are doing, if the app you are using has an "event" framework or similar you would need to use that, if you need it blocking/non-blocking, if time is important, how your calling code should manipulate the result...
Your gevent and threading are on the right track, because a function does what it is programmed to do, either accepting 1 var at a time or taking a set and returning either a set or a var. The function has to be called to return either result, and the continuous stream of processing is probably taking place already or else you are asking about a loop over a kernel pointer or something similar, which you are not, so ...
So, your calling code which encapsulates your function is important, the function, any function, eg, even a true/false boolean function only executes until it is done with its vars, so there muse be a calling function which listens indefinitely in your case. If it doesn't exist you should write one ;)
Calling code which encapsulates is certainly very important.
Folks aren't going to have enough info to help much, except in the super generic sense that we can tell you that you are or should be within in some framework's event loop, or other code's loop of some form already- and that is what you want to be listening to/ preparing data for.
I like "functional programming's," "map function," for this sort of thing. I think. I can't comment at my rep level or I would restrict my speculation to that. :)
To get a better answer from another person post some example code and reveal your API if possible.