[Tutor] How to change the values in python code?

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 2 20:03:35 EDT 2022


On 02/11/2022 19:39, samira khoda wrote:

> And then split it where the value of the last is less than previous. But
> when I run the code prints 0 for previous 

You never print previous.

in each line which technically
> says should not be split anywhere. I did a manual check up and I know there
> are various spots that the split should happen.


It might help if you post a few lines of sample data including some
lines where the last < previous and others where it is not.
> 
> How can I make the value of the previous update to the value of the
> previous timestamp and not stay zero for every line?

There are seeral issues in your code:

> Import pandas as pd

That should be lower ase import. Please post actual code not
retyped. It avoids wasting time on typos that don't exist
in the real thing.

> previous=0
> i=0
> data=open('time-.txt', mode="r")

Notice that there is no value for last at this point.

> for line in data:
>     x=line.split(", ")
>     last=int(x[7])

You assign it here but if the file were empty it would not exist.

However, as written, this is your complete loop.
You simply iterate over each line in the file then exit the
loop with last assigned to the 8th field of the last line.
What does the last line of your data look like?
It must have at least 8 fields or you'd get an error...
But the fields could be from any old string. Of course there
must be a number or the int() call would fail. But is it valid?

> if last < previous :

Now you never changed previous during the loop so it is still 0.
and last is the value from the last line of the file.
So the if block will only execute if the last value is negative.
Is that likely?

>     print("split here"+i)

i is never changed in the loop either so i is also zero.
But i is not previous!

>     previous=last
>     i=i+1

These lines change the variables but its too late, we are
at the end of the code.

And worryingly you have not closed the file.

Things to change?
1) Use a with statement for opening the file - then you don't
need to worry about closing it.

2) Move the if statement and block inside the loop.
But consider whether you really only want the previous
and i increment to be done when last < previous?

3) put more print statements in. Especially put
in

print("last = ", last)
print("previous = ", previous)

Just before the if statement.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list