[Tutor] Need help to print outputs on seperate files and avoid some unwanted error messages which can stop my code at some mid point

Alan Gauld alan.gauld at yahoo.co.uk
Thu Feb 27 18:59:52 EST 2020


On 27/02/2020 20:53, SATYABRATA DATTA wrote:
> There is some code
> *import math class Vector(): def __init__(self,vx,vy,vz): self.x=vx
> self.y=vy self.z=vz def norm(self): xx=self.x**2 yy=self.y**2 zz=self.z**2
> return math.sqrt(xx+yy+zz)*
> 

Please always post in Plain text to the tutor list - especially if
including code. Otherwise, the whitespace gets mangled as above
and it all becomes a meaningless mess.


> Now in the run file
> *import math*
> *import numpy as np*
> 
> *from Desktop import Test*

This is probably a bad idea. I assume you have not actually created a
package called Desktop but rather have just saved your Test module to
your GUI desktop?

While it may work its likely to go horribly wrong in the future,
especially if anyone else tries to run your code.
Its much better to create a project directory and save
your modules there (and run your code from there)

Nothing to do with your immediate issue but I thought it
worth pointing out!


> *def random_range(n, min, max):*
> *return min + np.random.random(n) * (max - min)*
> *filenumber = 0*
> *x=random_range(20,2,9)*
> *y=random_range(20,2,9)*
> *z=random_range(20,2,9)*
> 
> *trial_args = np.stack((x, y, z), axis=-1)*
> *for x, y, z in trial_args:*
> *    model=Test.Vector(x,y,z)*
> *    if model.norm() > 5:*
> *    filenumber += 1*
> *    filename = str(filenumber)*
> *    with open(filename+'.txt', 'w') as f:*
> *        print(x, y, z, '=>', model.norm(), *
> 

> causes my program to stop at some intermediate point. So my trick is to
> print each output to seperate files wherether errorful or right and than I
> can manually search which outputs are ok for me

There are numerous ways to do this but the easiest is probably just to
open two output files and write the strings(*) (rather than using print)
to whichever file is appropriate.

file.write() requires strings so you will need to convert
x,y,z etc to a string using str(). Thats one advantage of
using print, it does that for you.

-- 
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