tags:

views:

193

answers:

7

Hi,

I have a background in C++ and Java and Objective C programming, but i am finding it hard to learn python, basically where its "Main Function" or from where the program start executing. So is there any tutorial/book which can teach python to people who have background in C++ or Java. Basically something which can show if how you were doing this in C++ and how this is done in Python.

OK i think i did not put the question heading or question right, basically i was confused about the "Main" Function, otherwise other things are quite obvious from python official documentation except this concept.

Thanks to all

+5  A: 

Dive into Python is a good start. I wouldn't recommend to someone with no programming experience, but if you have coded in another language before, it will help you learn python idioms quickly.

kgiannakakis
I have read that book but the thing which is confusing me the most is that where the hell is "Main" in Python?
itsaboutcode
That's because there isn't one.
Lennart Regebro
Python doesn't have a "main()" like you're probably used to with Java or C++. There is the boiler plate - "if __name__ == "__main__":", but you can think of the Python interpreter as the "main()" that you're used to.
rnicholson
A: 

I started Python over a year ago too, also C++ background.

I've learned that everything is simpler in Python, you don't need to worry so much if you're doing it right, you probably are. Most of the things came natural.

I can't say I've read a book or anything, I usually pested the guys in #python on freenode a lot and looked at lots of other great code out there.

Good luck :)

Prody
A: 

I second Dive in to Python as a resource. As for the main function, there isn't one. The "main" function is what you write in the script you run.

So a helloworld.py looks like this:

print "Hello World"

and you run it with

python helloworld.py

That's it!

Lennart Regebro
+10  A: 

When you run a script through the Python interpreter (or import that script from another script), it actually executes all the code from beginning to end -- in that sense, there is no "entry point" to a Python script.

So to work around this, Python automatically creates a __name__ variable and fills it with the value "__main__" when you are running a script by itself (as opposed to something else importing that script). That's why you'll see many scripts like:

def foo():
    print "Hello!"

if __name__ == "__main__":
   foo()

where all the function/class definitions are at the top, and there is a similar if-statement as the last thing in the script. You are guaranteed that Python will start executing the script from top-to-bottom, so it will read all of your definitions there. If you wanted, you could intermingle actual functional code inside all the function definitions.

If this script was named bar.py, you could do python bar.py at the command line and you would see the script print out "Hello!".

On the other hand, if you did import bar from another Python script, nothing would print out until you did bar.foo(), because __name__ was no longer "__main__" and the if-statement failed, thus foo was never executed.

Mark Rushakoff
That's just about the ugliest hack I think I've seen in any language.
Robert Harvey
What do you have against underscores? :-)
Lennart Regebro
Thanks man, i think i was looking for this. may be i was trying to ask this. Other things just take 30 min to know but i was really really confused on this. Thanks again.
itsaboutcode
You wrote "so to work around this"..I don't see it as a workaround, it's working as intended. This is just the way scripting languages work.
Prody
@Prody: To work around the fact that there is no entry point in a script, and to (for all intents and purposes) make the script act as though there *was* an entry point, such as in C/C++/etc.
Mark Rushakoff
@Mark: I think that behavior is not to simulate an entry point. Here's an example usage for which I think it was made: You have a library with this file which holds a class. After the class definition, you could check if it's `__main__`, and if so, show some example usage.I'm just guessing here, correct me if I'm wrong tho :)
Prody
@Prody: it depends. In your Python library folder, `random.py` runs a test if it is `__main__`, for instance. On the other hand `calendar.py` prints out this year's calendar. Many scripts are intended only for importing, but there are many scripts that are fully functional on their own (while still generally intended to be imported).
Mark Rushakoff
@Prody: That's one case, yes. The usage is to make it possible to both use a module as a library and as a main file, you are correct.
Lennart Regebro
+1  A: 

If you are quite familiar with several languages like C++ and Java, you may find it easy to follow the official Python Tutorial. It is written in a classical language description bottom-up style from the lexical structure and syntax to more advanced concepts.

The already mentioned Dive Into Python takes a top-down approach in learning languages starting from a complete program that is obscure for a beginner and diving into its details.

Andrey Vlasovskikh
+1  A: 

The pithiest comment I guess is that the entry point is the 1st line of your script that is not a function or a class. You don't necessarily need to use the if hack unless you want to and your script is meant to be imported.

whatnick
+6  A: 

Excellent answer, but none points out what I think is one key insight for programmers coming to Python with background in other languages such as Java or C++: import, def and class are not "instructions to the compiler", "declarations", or other kind of magical incantations: they're executable statements like any other. For example, the def statement:

def f(x): return x + 23

is almost exactly equivalent to the assignment statement:

f = lambda x: x + 23

(stylistically the def is preferable as it makes f.__name__ meaningful -- that's the "almost" part; lambda is rather limited and should only ever be used when you're really keen to make an anonymous function rather than a normal named one). Similarly,

class X(object): zap = 23

is equivalent to the assignment:

X = type('X', (), {'zap': 23})

(again, stylistically, class is preferable, afford more generality, like def it allows decoration, etc, etc; the point I'm making is that there is semantic equivalence here).

So, when you run a .py file, or import it for the first time in a program's run, Python executes its top-level statements one after the other -- in normal good Python style, most will be assignments, def, class, or import, but at least one will be a call (normally to a function) to execute that function's body of code (def, like lambda, just compiles that code; the compiled code object only executes when the function or lambda is called). Other answers have already suggested practical considerations such as testing __name__ in order to make a module that can either be run directly or imported, etc.

Finally, it's best to have all "significant" code in functions (or methods in classes), not just stylistically, but because code in a function executes significantly faster (since the Python compiler can then automatically optimize all accesses to local variables). For example, consider...:

import time

lotsotimes = range(1000*1000)

start = time.time()
for x in lotsotimes:
  x = x + x
stend = time.time()

print 'in module toplev: %.6f' % (stend - start)

def fun():
  start = time.time()
  for x in lotsotimes:
    x = x + x
  stend = time.time()

  print 'in function body: %.6f' % (stend - start)

fun()

On my laptop, with Python 2.6, this emits:

in module toplev: 0.405440
in function body: 0.123296

So, for code that does a lot of variable accesses and little else, running it in a function as opposed to running it as module top-level code could speed it up by more than 3 times.

The detailed explanation: at module-level, all variables are inevitably kept in a dictionary, so each variable access is a dict-access; local variables of a function get optimized into a special array, so access is faster (the difference is even more extreme than the 20% or so speed-up you'd see by accessing an item in a Python list vs one in a Python dict, since the local-variable optimization also saves hashing & other ancillary costs).

Alex Martelli
"code in a function executes significantly faster (since the Python compiler can then automatically optimize all accesses to local variables)." Interesting
foosion
@foosion, I've edited the answer to add an example of speed-up obtained by moving code from module top-level to function body, and a brief explanation of why that is the case.
Alex Martelli
Just out of curiosity, where does "stend" come from?
uvts_cvs
@uvts_cvs, just a silly old conceit of mine (I often use start and stend as the variable names to snapshot times just before and after some activity) -- the similarities of the names remind me of their connection. `finis` would be more meaningful but I've found it confuses some readers (who miss the Latin reference). I do want two short names, preferably of the same length, that won't accidentally clash with names I could be using for something else in the block I'm timing (and I never use those for anything _but_ timing;-).
Alex Martelli