Python Continue the loop from start when the condition is false - python

This is the continuation of my previous question where it was not that clear what I want to do.
Now please find the Full code here I know this code is very crude as I am new to programming . I am sure this code can be written in another way more optimally but I am not that experienced.
Now my question is I will be running this code from Python shell.
while 1 ==1:
execfile('adhocTest.py')
This code consists of two parts 1. Prerequisite 2. Main program.
The prerequisite is to copy a template Excel file and paste in a directory. Main program is to do some operation and result should be written onto this file and validate few cells. If the condition is true main program will keep continuing else I want that whole script should run again i.e Run pre requisite as well as main program. I am stuc at this point as of now if teh condition is false it exits the whole script.
As I said this code is crude if anyone helps me to optimize it I will be very happy. But this is secondary. I need the continuous run of this script when the condition is false.

You need to re-structure your program:
def call_me():
while True:
prerequisite()
main_operations()
if validate():
main_continuing()
or
def call_me():
while True:
prerequisite()
while validation():
main_operations()
This will loop around as you need it to.

Related

Why does using loop-only functions in a def section not work, even when in a loop?

I am making a small text-based game in Python. It involves many inputs and so to avoid bugs, there are a few things I have to check every time an input exists. Naturally, to speed up the process I wanted to put the code into a def in order to simplify the writing process. When I put the code in the def, it red underlines the continue and break commands (meaning they are incorrect), and if you run the code using the def name, a Traceback occurs. I have tried putting the def section at the beginning of the program, after the while True: (The program is supposed to run infinitely until a certain action is taken that breaks the loop) I have also made sure to try putting it under any variables referenced and in the loop so that no part of it is not defined and so that everything would work if I were to just put the code in there.
Here is the code I am trying to put into a def.
def input_bugs():
if letter_one.lower() == "done" and total_count == 0:
print("You have to play at least one game!")
continue
elif letter_one.lower() == "done":
break
elif len(letter_one) > 1:
print("Sorry, you gotta pick a single letter, no more. Otherwise, type 'done' to end the game and see your stats.")
continue
Here is the Traceback I get every time I try to run it.
line 20
continue
^^^^^^^^
SyntaxError: 'continue' not properly in loop
At this point, I don't even care if I have to write it out every time, I can just copy and paste. I am simply curious as to why it doesn't work so that I know in the future. In case you could not tell, I am pretty new to programming so I want to learn from any mistake I make. Also sorry if I referred to some things in the wrong way. Hopefully, you understood what I meant.

collecting data from running program

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.

Run Python script line-by-line in shell vs atomically

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.

PyCharm: debugging line by line?

I am using PyCharm (community version) for my Python IDE. I want the program to debug in a line-by-line fashion. So I don't want to set every line as a break point... Is there a way I could do this?
As #Cyber mentioned, the debugging hotkeys will let you step through line by line, step down into function calls, etc., once you've hit a breakpoint and stopped somewhere.
If you really want to step through each line, you could set a breakpoint somewhere at the very beginning of your code. If you're using a main() function in your code, e.g.:
def main():
....
if __name__ == '__main__':
main() # Breakpoint here, 'Step Inside' to go to next line
then you could set the breakpoint at the call to main(). (If you're not, you might want to try this approach.)
One other thing I'd point out is PyCharm's easy-to-overlook feature of conditional breakpoints. If you right-click on the breakpoint symbol in the gutter area of the editor, you can type in a condition, like n > 10; the breakpoint only triggers when that line is executed and the condition is met. When you're trying to debug code issues within a recursive function, say, this can simplify things a lot.
I know the last part isn't really what you were asking for, but as your codebase gets bigger, going through each line can get really time consuming. You'll probably want to focus more on things like unit testing and logging with larger projects.
To run in debug mode press the 'bug' button (or Shift + F9).
Step over - F8
Step into - F7
Step out - Shift+F8.
Step to next breakpoint (or end) - F9
The pdb module only needs 2 lines of code in your program to be able to step through line by line.
import pdb # Insert this as the first line of your program
pdb.set_trace() # Insert this once in your program to step through it
# code you want to step into
This youtube video explains everything in 6 mins.
As mentioned above you can use the hotkeys, alternatively, you can use the debugger UI:
The blue arrows on the top allow you to step over, step into, or step out.

Python File append error

This code works fine for me. Appends data at the end.
def writeFile(dataFile, nameFile):
fob = open(nameFile,'a+')
fob.write("%s\n"%dataFile)
fob.close()
But the problem is when I close the program and later run again I found that all the previous data were lost. Process is started to write from the start and there is no data in the file.
But during the run it perfectly add a line at the end of file.
I can't understand the problem. Please some one help.
NB: I am using Ubuntu-10.04 with python 2.6
There is nothing wrong with the code you posted here... I tend to agree with other the comments that this file is probably being overwritten elsewhere in your code.
The only suggestion I can think of to test this explicitly (if your use case can tolerate it) is to throw in an exit() statement at the end of the function and then open the file externally (aka in gedit) and see if the last change took.
Alternatively to the exit, you could run the program in the terminal and include a call to pdb at the end of this function which would interrupt the program without killing it:
import pdb; pdb.set_trace()
You will then have to hit c to continue the program each time this runs.
If that checks out, do a search for other places this file might be getting opened.

Categories

Resources