Python for C++ or Java Programmer

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


Asked by: Freddie771 | Posted: 06-12-2021






Answer 1

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.

Answered by: Abigail150 | Posted: 07-01-2022



Answer 2

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

Answered by: Ryan726 | Posted: 07-01-2022



Answer 3

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.

Answered by: Miranda593 | Posted: 07-01-2022



Answer 4

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.

Answered by: Max304 | Posted: 07-01-2022



Answer 5

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

Answered by: Ned740 | Posted: 07-01-2022



Answer 6

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!

Answered by: First Name649 | Posted: 07-01-2022



Answer 7

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.

Answered by: Dexter383 | Posted: 07-01-2022



Similar questions

C++ or Python for C# programmer?

Closed. This question is opinion-based. It is not c...


Python for a Perl programmer

I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone w...


Perl for a Python programmer

I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) w...


python - how real programmer do server loop?

everytime when running this program, I hear my cpu fan is boosting. I suspected the busy waiting while loops in the code is the cause. I wonder how a real programmer will do to optimize this? from multiprocessing import Process, Queue import threading class PThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) #view leave will set this event self.event =...


Python Programmer test

Closed. This question does not meet Stack Overflow guid...


python - Noob programmer can't figure out simple issue

Closed. This question needs debugging detai...


vba - Resources for Python Programmer


Now that Python 2.6 is out, what modules currently in the language should every programmer know about?

A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in Python 2.6), for instance, are found in the collections module. The Library Documentat...


Advice for C# programmer writing Python


C++ or Python for C# programmer?

Closed. This question is opinion-based. It is not c...


java - asm / C / Python / Perl / Lisp / Scheme Programmer looking for something new to learn

Closed. This question does not meet Stack Overflow guid...


Python for a Perl programmer

I am an experienced Perl developer with some degree of experience and/or familiarity with other languages (working experience with C/C++, school experience with Java and Scheme, and passing familiarity with many others). I might need to get some web work done in Python (most immediately, related to Google App Engine). As such, I'd like to ask SO overmind for good references on how to best learn Python for someone w...


Perl for a Python programmer

I know Python (and a bunch of other languages) and I think it might be nice to learn Perl, even if it seems that most of the people is doing it the other way around. My main concern is not about the language itself (I think that part is always easy), but about learning the Perlish (as contrasted with Pythonic) w...


Newbie Python programmer tangling with Lists

Here's what I've got so far: # A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(words): counter = 0 for word in words: if len(word) >= 2 and word[0] == word[-1]: counter += counter retur...


php - Old desktop programmer wants to create S+S project

I have an idea for a product that I want to be web-based. But because I live in a part of the world where the internet is not always available, there needs to be a client desktop component that is available for when the internet is down. Also, I have been a SQL programmer, a desktop application programmer using dBase, VB and Pascal, and I have created simple websites using HTML and website creation tools, such as Frontpage...


Proper way to do session handling in Python + Pylons for a php programmer

I'm a php programmer who's just getting started with Python. I'm trying to get Python to handle login/logout via database-stored sessions. Things work, but seem inconsistent. For example, sometimes a user isn't logged out. Sometimes users "switch" logins. I'm guessing this has something to do with thread-safety, but I'm just not sure where to begin on how to fix this. Any help would be appreciated. Here's what I hav...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top