Python nested while loop - python-3.x

Being a beginner with Python (Python 3.x), I was trying and getting my hands dirty with the while loop, when I ran into a small snag - no doubt due to my inexperience with the language - the code runs in a continuous loop!
The code is as follows :
n=0
while (n<len(txt)) :
while (n<5) :
#t = txt[n].value
#print(t)
n=n+1
print(n)
In the program, n is a control variable. txt is a list which stores the values extracted from my excel sheet. The aim of the program is to loop through the contents of each cell in the column of the sheet (represented by the list txt).
However, due to some silly mistake in this code, Python seems to run into an endless loop. Any help will be greatly appreciated.
P.S. the 5 in the inner loop is just representative of a number I will loop through again.

This seems to work perfectly fine now :
n=0
while (n<len(txt)) :
if n==50:
break
while (n<50) :
#t = txt[n].value
#print(t)
n=n+1
print(n)
Thanks ybdesire! (y)
One small question thought - why does the Spyder editor not return back to the next console command line, some times, despite having finished execution ?

Related

Stepping through with F8 the code runs, stops in standard execution with F5

I've written a macro which sums numbers, grouping by year and by month based on our projection model.
It runs from start to end when stepping through with F8.
It stops immediately in standard execution with F5.
The first trouble is
Runtime error 91
in
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
Originally I tried Application.WorksheetFunction.Match(...) but had the same problem: runs in debug, but not in execute (Error 1004 instead).
I considered it could have been an Excel version issue (the Match function has a different name in the Italian version). I switched to a more neutral Find, but still no luck.
When you have an error with a line that is a combination of several commands, try breaking it down into the individual steps.
For example, this works:
Sub findDemo()
Const toFind = "blah"
Dim rg As Range, f As Range
Set rg = Range("A2:C5")
Set f = rg.Find(toFind)
If f Is Nothing Then
Stop 'not found
Else
Debug.Print "found in column #" & f.Column
End If
End Sub
Also see the example in the documentation for Range.Find().
Welcome to SO. Sometimes Excel reads code faster than executing, so when reading a command there is a previous one not finished. IT's weird but it happens a lot if your code does a lot of stuff and calculus.
Besides, when debugging, every command line is executed before reading next one, so you cannot detect this just debugging.
So if your code runs perfect when debugged but errors if executed as normal, try to add the command DoEvents right before the problematic line. Something like this:
' your previous code
'
'
'
Doevents
issmIndex = Range("A1:Z1").Find("ck.IssMon").Column 'issmIndex an integer
'
'rest of your code
This commands forces Excel to make sure everything has been executed before reading. It's kind of like a checkpoint, something like make sure you've done everything before going to next line.
DoEvents
function

Using nohup to help run a loop of python code while disconnecting from ssh

I'm looking for help running a python script that takes some time to run.
It is a long running process that takes about 2hours per test observation. For example, these observations could be the 50 states of the usa.
I dont want to baby sit this process all day - I'd like to kick it off then drive home from work - or have it run while I'm sleeping.
Since this a loop - I would need to call one python script that loops through my code going over each of the 50 states - and a 2nd that runs my actual code that does things.
I've heard of NOHUP, but I have very limited knowledge. I saw nohup ipython mypython.py but then when I google I get alot of other people chiming in with other methods and so I don't know what is the ideal approach for someone like me. Additionally, I am essentially looking to run this as a loop - so don't know how that complicates things.
Please give me something simple and easier to understand. I don't know linux all that well or I wouldn't be asking as this seems like a common sort of command/activity...
Basic example of my code:
Two files: code_file.py and loop_file.py
Code_file.py does all the work. Loop file just passes in the list of things to run the stuff for.
code_file.py
output = each_state + ' needs some help!'
print output
loop_file.py
states = ['AL','CO','CA','NY','VA','TX']
for each_state in states:
code_file.py
Regarding the loop - I have also heard that I can't pass in parameters or something via nohup? I can fix this part within my python code....for example reading from a CSV in my code and deleting the current record from that CSV file and then re-writing it out...that way I can always select the top record in the CSV file for my loop (the list of states)
May be you could modify your loop_file.py like this:
import os
states = ['AL','CO','CA','NY','VA','TX']
for each_state in states:
os.system("python /dir_of_your_code/code_file.py")
Then in a shell, you could run the loop_file.py with:
nohup python loop_file.py & # & is not necessary, it just redirect all output of the file to a file named nohup.out instead of printing it on screen.

Semantic guess the number game errors - Python3.x

I am 11 years old and am keen programmer learning Python.
1) I am programming a guess the number game and when I ask the user if they want to play again, I get a semantic error (I think this is the correct way to describe it) where if I input "no", "n", "NO" or "N", the if statement is still executed, causing the loop() function to run again, after calculating scores. Take a look at the following image (sorry about the cluttered windows).
Play again error: https://i.stack.imgur.com/TsEyw.png
Here is a link to the rest of the program:
https://gist.github.com/anonymous/f9be138e07c569b8721b990293d92314 (I only have 8 reputation points) , but I am looking at just this snippet:
def play_again():
again = input("\nWould you like to play again? y/n " + prompt)
if again.upper() == "Y" or "YES":
global gu_num
percent = gu_num * 10
score = 100 - percent
highscores = [{round: (score)}]
current_score = {round: (score)}
highscores.append(current_score)
print("Lets see if you can beat your score of " + str(current_score[round]) + ".\nHere we go!")
gu_num = 0
loop()
elif again.upper() == "N" or "NO":
print("Ok then.\nThank you for playing Guess The Number and I hope to see you again soon!\nThis game was created and devoloped by Kiran Patel (me), age 12. If you liked this game or want to talk to me about -->anything<--, please do email me at kiran#inteleyes.com. It'll make me happy! Thank you for playing Guess the number with me.\n\n program was developed by Kiran Patel in 2017 ad.")
input("\n\nPress the enter key to exit")
quit()
else:
print("Sorry, I don't understand. Please try again:")
play_again()
2) I'm having a similar problem with the part of my code which starts to handle files. When I input a 'no' (same if expression) the program will execute the part of that if statement which creates the file (take a look at this image: file saving result and this image: file operations code). Note that the 'file operations code' image prints out the file-save error message because I hadn't given perms to write in prog'/files folder. I know it has tried to save the file because of the error message that was printed out (I intended the error message to be printed out).
3) Also, does anyone know what #!/usr/bin/python means? I know its hashtagged out, but I have seen it before like this and I was wondering what it means.
As always, ANY help will
be appreaciated, so please don't hesitate on adding something that is not directly relevant to the question, because I may well have missed it (unless it is completely irrelevant).
Once again, thanks in advance for your help.
From Kiran
The problem is here (and on every line that looks like it):
if again.upper() == "Y" or "YES":
Here's what you (reasonably) assume it's doing (This is how you would fix it, btw):
if (again.upper() == "Y") or (again.upper() == "YES"):
Here's what it's actually doing:
if (again.upper() == "Y") or "YES":
So let's say that you typed Q at the prompt. As Python reads along the line, it sees the first comparison operator, ==, and compares just the two things on either side of it: "Q" and "Y". "Those are not equal", thinks Python, and moves on to the next part: comparing False - the answer to the first part - with "YES".
In Python, if something exists and isn't False or 0 or something similar, it gets treated as True. "False is False, but "YES" is a perfectly valid string", thinks Python. "and the or operator means that if either of these two things is True, the whole thing is True, so this must all be true and I should run this block of code now." And so it does, every time, no matter what you type.
As a general rule, when you're doing these kinds of tests, it's only safe to do one comparison at a time. Any more than that and it's time to bring in the parentheses.
Also, regarding #!/usr/bin/python: the #! is called a Shebang, and it's not part of Python at all - it's part of your operating system (assuming your operating system isn't Windows). It says to your OS: "This may look like an ordinary text file, but it's actually a script, which you should run using the program located at /usr/bin/python".

Fortran error check on formatted read

In my code I am attempting to read in output files that may or may not have a formatted integer in the first line of the file. To aid backwards compatibility I am attempting to be able to read in both examples as shown below.
head -n 3 infile_new
22
8
98677.966601475651 -35846.869655806520 3523978.2959464169
or
head -n 3 infile_old
8
98677.966601475651 -35846.869655806520 3523978.2959464169
101205.49395364164 -36765.047712555031 3614241.1159234559
The format of the top line of infile_new is '(i5)' and so I can accommodate this in my code with a standard read statement of
read(iunit, '(I5)' ) n
This works fine, but if I attempt to read in infile_old using this, I as expected get an error. I have attempted to get around this by using the following
read(iunit, '(I5)' , iostat=ios, err=110) n
110 if(ios == 0) then
print*, 'error in file, setting n'
naBuffer = na
!rewind(iunit) #not sure whether to rewind or close/open to reset file position
close(iunit)
open (iunit, file=fname, status='unknown')
else
print*, "Something very wrong in particle_inout"
end if
The problem here is that when reading in either the old or new file the code ends up in the error loop. I've not been able to find much documentation on using the read statement in this way, but cannot determine what is going wrong.
My one theory was my use of ios==0 in the if statement, but figured since I shouldn't have an error when reading the new file it shouldn't matter. It would be great to know if anyone knows a way to catch such errors.
From what you've shown us, after the code executes the read statement it executes the statement labelled 110. Then, if there wasn't an error and iostat==0 the true branch of the if construct is executed.
So, if there is an error in the read the code jumps to that statement, if there isn't it walks to the same statement. The code doesn't magically know to not execute the code starting at label 110 if there isn't an error in the read statement. Personally I've never used both iostat and err in the same read statement and here I think it's tripping you up.
Try changing the read statement to
read(iunit, '(I5)' , iostat=ios) n
You'd then need to re-work your if construct a bit, since iostat==0 is not an error condition.
Incidentally, to read a line which is known to contain only one integer I wouldn't use an explicit format, I'd just use
read(iunit, * , iostat=ios) n
and let the run-time worry about how big the integer is and where to find it.

Python IDLE won't run the code

The code I had wasn't executing whatsoever. So, I tried it with a basic code:
x=10, if x==10:, print ("Hello"),
This worked. But the moment I extended it to anything else, it wouldn't run eg.:
count=0, x=10, if x==10:, count=count+1, if count == 10:, print ("Hello"),
(That had correct indents and exc. the commas.) The loop wouldn't loop.
Anyone understand why? The other queries similar to this regard a different issue. It won't run through CMDLine either. I did uninstall and reinstall it but that changed nothing.
The reason your loop won't run is because there isn't a loop. I think what you're trying to do is this.
for i in range(11):
if i == 10:
print('Hello')
With the current string of commands that you're running, count is simply being increment from 0 to 1, and since count != 10 at that point, you never see Hello.

Resources