Hello,

I know this is something extremely easy to do but i don't master the python syntax at the moment. I've read the documentation and I've been searching on the 'net for information but nothing that I've found seems to be what I'm looking for. Probably the reason is the fact that what i am trying to do is something that any programmer knows but since i only know C/C++, python is somewhat different to me. I really like it but i need to get used to (and learn more about) the way that you specify (or actually don't specify) the data types you are working with.

This is what i managed to write (I've also read part of the "Starting Python" thread here):

def getlist():
    nrlist=[]
    while True:
        aux=data.readline()
        if aux==EOF:
            return list
        try:
            n=float(aux)
            nrlist.append(n)
        except ValueError:
            print "Introdu date numerice!" #Its in romanian.. meaning "Enter numeric data!."

data=open(data,"r")
list=[]
list=getlist()
print list

The error I'm getting is:

Traceback (most recent call last):
  File "[not relevant]\workspace\primul\src\primul.py", line 21, in <module>
    data=open(data,"r")
NameError: name 'data' is not defined

I apologize if I am wasting your time with such an easy question but I've figured that I'll win some time if I get an exact answer from you then searching on and on and trying various ways of writing the code.


Thank you for your help!

While you don't need to specifically declare variables, you still need to make sure that you've got them in the correct scope.

So first thing I notice is that your function us trying to read from data; however data doesn't exist in your function, only in the part that calls the function. A way around this would be to pass data to getList via getList( data ) , which would require a change to the line def getList( data ): , naturally...

Now your problem is that you're opening data, but haven't declared what data is. But also, you say data=open(data, "r") ... which is not good form. open() will return a file handle to data. But you've initially intended data to contain the name/path of the file. This means that after opening the file, if you wanted to re-use the filename or path (which ever data was supposed to be), it would be erased and instead you'd be dealing with the file handle.

Do something like this

my_file = '/usr/data/file_fun.txt'
data = open( my_file, 'r' )

list = getList( data )

I suggest a slight modification to your function, as you can make use of Python's built-in file iteration, instead of rolling your own.

def getlist( data ):
    nrlist=[]
    for each_line in data:
        try:
            nrlist.append( float( aux ) )
        except ValueError:
            print "Introdu date numerice!" #Its in romanian.. meaning "Enter numeric data!."
    return list

Python knows that when a file handle is iterated over, that it should iterate line by line (so the use of each_line was arbitrary, it's just for your understanding... it could've just as well been r, or n or your favorite variable name...)

You can also reduce the float() and append() calls into a single line for simplicity.

Finally, by placing return list outside of the for loop, it will return once processing has completed. Now, when you called the function via list = getList() you should verify that the function returned some values via:

if not list:
    print "No numerical entries found!"

This brings me to my final suggestion. See how the word "list" is highlighted in purple in your block of code (and mine)? That is a clue that list is a reserved word. Look at the following:

>>> list("12345")
['1', '2', '3', '4', '5']
>>> a = (1,2,3,4,5)
>>> list(a)
[1, 2, 3, 4, 5]
>>>

list, int, float, str, chr, etc.... these are all instances of class types that will convert things into the specified class, and thus should not be used as variable names. By declaring a variable as list, you lost the ability to ever use list() later on in the program.

HTH!

Here is a more pythonic approach

def getlist(file):
    nrlist = []
    try:
        for line in file:
            n = float(line)
            nrlist.append(n)
    except ValueError:
        raise ValueError("Introdu data numerice!")
    return nrlist

data = open("data.txt")
list = getlist(data)
print list

Some remarks -- you don't need readline to iterate over the lines of a file, the idiom for line in file does the trick. -- If you prefer to use readline , remember that readline returns the empty string "" at the end of the file, and not EOF. -- note that I can put the try ... except structure outside of the loop, which is faster, and errors will be caught as well.. -- More important, often in python code, it's better to let the exception propagate to the calling environment than to catch the exception. I would probably have written this myself without a try statement and let ValueError propagate to the caller. The reason is that your try ... except statements just prints an error message, but then returns only a partial list to the caller, so that after your line list = getlist() , your program would continue with a list truncated at the line of the error, which is not better than having an exception propagate. However, since I want to put your error message, instead of printing the message, I raise a new ValueError with the error message, so that if your file contains non numeric data, the user will be informed as well.

After some time with python you will write your program like this

mylist = [ float(line) for line in open("data.txt") ]
print mylist

Also, I forgot to mention that it's better to avoid 'list' and 'file' as variable names, because they are the names of 2 standard types.

Thank you!
If I'll have some more questions, I'll ask if I can't find the answer here, on the forum or via Google.

One more thing:
In python, a list is like a vector in C?

One more thing:
In python, a list is like a vector in C?

It is similar in that it has built-in functionality for appending, inserting, removing, etc.

I'm trying to do the projects in the "Projects for the beginner" thread.
I've skipped the code library because I don't really get it :-s. [if you can i explain, i would appreciate it :).]
I'm thinking to start the converter. I've read about dictionaries in Python on the Internet but i don't know how that would help me. Should i create a dictionary like d={"inchtocm":2.54,"metertocm":100} and then look for the formulas in the dictionary? Or what?

Some things in python are so different from C.. heh.

Here's a little example of using a dictionary:

>>> d = {"inchtocm":2.54, "metertocm":100}
>>> d.keys()
['metertocm', 'inchtocm']
>>> d.values()
[100, 2.54]
>>> for elem in d:
...     print elem, d[elem]
...     
metertocm 100
inchtocm 2.54
>>> d["foottoinch"] = 12
>>> for elem in d:
...     print elem, d[elem]
...     
foottoinch 12
metertocm 100
inchtocm 2.54
>>> feet = 5
>>> inches = feet * d["foottoinch"]
>>> inches
60
>>>

And why is this easier/more efficient than defining functions for each conversion? [Thinking like a C coder, i guess :-/..]
I mean, i could make a menu from where you can choose the conversion you want to apply and then enter the desired number and that would be calling one of the function.

Thanks for the example! :)

I think in C you would write code like

static double inchtocm = 2.54;

The difference, is that python structures are much more dynamic and easier to manipulate than C structures. On the other hand, C code stays very close to machine level, which is very efficient at run to time. In python, you try to minimize development and maintenance effort.

One more thing:
In python, a list is like a vector in C?

Unlike the vector in C++, a python list is simply an indexed container, the indexed elements in a list can be any object of any type.

Here are some standard operations you can apply to a list or sequence s:

s[i] = x  item i of s is replaced by x     
s[i:j [:step]] = t  slice of s from i to j is replaced by t     
del s[i:j[:step]]  same as s[i:j] = []    
s.append(x)  same as s[len(s) : len(s)] = [x]
  appends to the end of a list, same as s += [x]
  s[:0] = [x] adds to the start of a list    
s.extend(x)  same as s[len(s) : len(s)] = x
  (extend one list with another list) 
s.count(x)  return number of i's for which s[i] == x
  for instance count number of duplicates    
s.index(x[, start[, stop]])  return smallest i such that s[i] == x 
  start and stop limit search to only part of the list  
s.insert(i, x)  same as s[i:i] = [x] if i >= 0 
  also i == -1 inserts x before the last element    
s.remove(x)  searches for first x in the list and removes it
  same as del s[s.index(x)]
s.pop([i])  same as x = s[i]; del s[i]; return x
  i defaults to last element  
s.reverse()  reverse the items of s in place  
s.sort([cmpFunc])  sort the items of s in place (s will change), 
  can specify the compare function
  to make sense, items to be sorted should be of same type  
separator.join(seq)  Returns a concatenation of the strings in 
  the sequence seq, separated by string separator, 
  e.g.: ", ".join(['A', 'B', 'C']) -> "A, B, C"

Thank you, guys!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.