Give Python a try. It's simple and readable enough that anyone can pick it up, yet powerful enough for whole businesses to rely on it.
Python.org if you're interested, and if you're looking for a fun way to learn (i.e not through reading gigantic, often dense textbooks), try the Python Challenge.
Send a HEAD request.
e.g. using requests
>>> import requests >>> resp = requests.head('http://www.python.org') >>> print(resp.status_code) 301
I'm sorry, but that's the opposite of "pythonic".
Magically adding all created users to some hidden list, preventing them from being deleted ever and setting up for hilarious bugs when you decide to work with another set of users elsewhere in the program? Not pythonic, it obviously violates like four and a half of the rules.
Accessing that list by iterating over the class object (with the actual method implemented in a metaclass somewhere else)? Dude, WTF.
Make a, I don't know, Context
or Users
or whatever object representing your collection of users and give it an new_user
method that creates and adds a user. Then implement iteration as usual. That's it, no possibility for weird bugs, you always see where you pass your collection, and you don't have to use complicated, rarely used features to implement weird, unexpected functionality.
From http://www.python.org/static/humans.txt:
> Standards: HTML5, CSS3, W3C (as much as possible) > > Core: Python 3 and Django 1.5 > > Components: Modernizr, jQuery, Susy (susy.oddbird.net) > > Software: SASS and Compass, Coda, Sublime Text, Terminal, Adobe CS, Made on Macs > > Hardware Stack: Ubuntu 12.04, Postgresql 9.x, Nginx, Gunicorn > > Helpers: South, Haystack, Pipeline
Are you familiar with PEP-3107, function annotations, implemented by Python3? It provides some level of syntactic expressiveness for implementing some form of static type checking (static as in expressed in source code, but not static in the sense of a "pre-run" check).
Some interesting discussion on this Stackoverflow post
Nowadays most universities start students off with Java or Python. Those languages are both easy to learn while being versatile and they both see actual use in industry. However, it's more important that you understand the fundamentals of programming logic, control flow, data storage, etc. than any particular language.
If you want other things to study, look into discrete math and theory. Even something simple like knowing what a DFA is and their limitations would put you way ahead of the curve.
As an aside, this question isn't really suitable for this forum. /r/learnprogramming would probably be a better place to post this.
This is actually covered in PEP-328 If you're on Python 2.5 or later then you can use:
from future import absolute_import
and get pretty much exactly the behaviour you need. I believe this is standard in the 3.x series.
One of the nicer things in the Python community is code style consistency. PEP 8 is used for the standard library and although that's not necessary for user code, it's a nice guide nevertheless. One of the things it recommends is to avoid comparing boolean expressions with True/False. ;)
Your script works and that's what counts, but here are some tips anyway:
os.path.join()
for path concatenation instead of adding them together. This way you won't have to worry about missing or duplicate path separators in each part.os.path.splitext(s)[1]
to get the extension. Before comparing it, use os.path.normcase()
to convert it to the proper case instead of always using lower()
. This will handle the case sensitivity difference between Windows and Linux.'/'
in literal path strings. Windows accepts them just find and you can use os.path.normpath()
if you want to convert them to the native platform format (e.g. for displaying). It looks cleaner and, on Windows, it avoids the need for escaping the backslashes or using raw strings.You could also speed up the grouping()
function by splitting the extension strings once at the start of the script and using 'in'
instead of count()
to search for a match. count()
has to test all elements and although it doesn't matter for such a small number of items, it's (again) a matter of style.
EDIT: Also, the special Windows folders like the desktop and My Documents and localized and therefore you need to use a special function to get their real names if the system language is not english (in greek, for example, they are called "Επιφάνεια εργασίας" and "Τα έγγραφά μου" respectively). One way is to use shell.SHGetFolderPath()
from Mark Hammond's pywin32, which every Windows Python user should have installed.
Oh, and Keith's suggestions are also great.
Current Python
if case in [0]: print "You typed in zero" elif case in [1, 9]: print "a perfect square" elif case in [2]: print "an even number" elif case in [3, 5, 7]: print "a prime number" elif case in [4]: print "a perfect square" elif case in [6, 8]: print "an even number" else: print "Only single-digit numbers are allowed"
vs c-style switch
switch(n) { case 0: printf("You typed zero.\n"); break; case 1: case 9: printf("n is a perfect square\n"); break; case 2: printf("n is an even number\n"); case 3: case 5: case 7: printf("n is a prime number\n"); break; case 4: printf("n is a perfect square\n"); case 6: case 8: printf("n is an even number\n"); break; default: printf("Only single-digit numbers are allowed\n"); break; }
What are you gaining here from a syntax perspective?
In C-code, switches are a translation to an if-else chain and a convenience of syntax. Python doesn't benefit at all from this approach and it definitely is only worth adding new syntax if there's something special about it that isn't available already within the language. The advantages of the switch statement were going to fall under what the interpreter did behind the scenes (if it did anything at all).
PEP 3103 has most of the discussion in it. If you read through it, you'll gain a better insight.
I do plan on making this more user-friendly, trust me! =) If you're not comfortable running a Python script (and installing at least one extra Python module -- numpy, I believe), this is going to be difficult. Hopefully I can make a graphical interface for this by the time 1.8 is released.
If you have Python installed, you will need to download my code, open a command prompt, browse to the directory where you've extracted my code, and run two commands:
python bestofboth.py --find-edges minecraft/saves/world --edge-file edges.txt
This will examine the Minecraft world file in your "minecraft/saves/world" directory (relative to your location when you run the script -- if it makes it easier, imagine it says "c:\minecraft\saves\world" instead). The perimeter of the world will be stored in a special format in "edges.txt".
Now that the perimeter has been calculated, you can run the smoothing step -- given the same path to the same world, and given the edges.txt file you generated earlier, so it knows where the perimeter is that it's supposed to be smoothing:
python bestofboth.py --smooth minecraft/saves/world --edge-file edges.txt
This will turn those jagged perimeter cliffs into rivers. If you haven't explored your entire perimeter since upgrading to 1.8, some of the perimeter cliffs won't have been generated yet, so you'll need to type the exact same thing later on. You can do this as often as you want. Eventually, when you've discovered all of the cliffs, the script will say it has nothing left to do and that all chunks have been smoothed out.
Finally, just run Minecraft, look around your world, and observe that the jagged cliffs between your 1.7 and 1.8 lands have been turned into rivers. =)
Explain this "virtual environments"... I hadn't looked at PEP 405 before.
Am I missing something magical-groundbreaking-revolutionizing-gamechanging in how I package code?
I tend to go with the first one, but a mantra of Python is:
Explicit is better than implicit.
So IMO if the second one is clearer to you because it is more explicit, go with that.
All of these are great points that I think stem from some "values":
Really it all comes down to expression and readability. In Java and Perl, but especially Perl, it's much easier for your code to become difficult to read and process. This hurts not only other people trying to read your code later, but even yourself, even while you're writing it. This might seem secondary, or unimportant, but when you realize how much of coding is actually reading code, the purpose becomes clear. Python code tends to be very easy to process while maintaining incredible expressiveness.
The other really great part about Python is that it has a philosophy that guides design decisions. I can't express how awesome that is for the community, because arguments and debates can go back to that philosophy as a guiding force.
Essentially it means using Python to call into existing code or code being written in another language for various reasons. For instance, I might write the engine of a computer algebra system in C or C++ for performance reasons. However, the users of my CAS, e.g. mathematicians, find it easier to interact with that engine via Python, so I provide a Python layer over the engine that makes it easier for researchers to use.
Alternately, your company has just merged with another and you're trying to figure out how to get two legacy systems to talk to one another. You decide to add a translation layer between them, written in Python. You chose Python because it's fast to develop in and has excellent facilities for calling into native code.
Here's an essay about why Python makes a good embedded / glue language, albeit with a bit of Python evangelizing.
Python never "embraced" UCS-2. It was a compile-time option between 2-byte and 4-byte encodings, and in Python 3.3: "The Unicode string type is changed to support multiple internal representations, depending on the character with the largest Unicode ordinal (1, 2, or 4 bytes) in the represented string. This allows a space-efficient representation in common cases, but gives access to full UCS-4 on all systems."
EDIT: Python's original Unicode used UTF-16, not UCS-2. The reasoning is described in http://www.python.org/dev/peps/pep-0100/ . It says "This format will hold UTF-16 encodings of the corresponding Unicode ordinals." I see nothing about a compile-time 2-byte/4-byte option, so I guess it was added later.
http://www.python.org/dev/peps/pep-0008/
CapWords for classes and exceptions (because exceptions are classes).
lower_case_with_underscores for function names.
lower_case_with_underscores for variables.
UPPER_CASE_WITH_UNDERSCORES for constants.
The primary reason would have been the "There should be one-- and preferably only one --obvious way to do it." rule.
A likely secondary reason is that switch
was popularized in C because it indicated to compilers that they should make an effort to optimize it using a jump table. Compilers evolved to also handle repeated else if
statements for this optimization, so switch
quickly lost its advantage. It slightly helps readability in some cases, but it's really not worth adding a new language construct for such a minor bit of syntax sugar.
If you haven't already, I'd recommend reading the PEP for yield from. PEPs usually describe the need for a new feature.
To summarise it: if you're just yielding values back from another iterable, it was already easy to use a for loop. But you can do some clever things with generators using the less-well-known send()
and throw()
methods. If you want to split out part of your generator into a separate function, the code needed to properly delegate send() and throw() calls was horribly complicated. Now you can just do yield from mysubgenerator
and values are sent to the right place.
From PEP 394 (http://www.python.org/dev/peps/pep-0394/ )
This PEP provides a convention to ensure that Python scripts can continue to be portable across *nix systems, regardless of the default version of the Python interpreter (i.e. the version invoked by the python command).
python2 will refer to some version of Python 2.x python3 will refer to some version of Python 3.x python should refer to the same target as python2 but may refer to python3 on some bleeding edge distributions
Not following Python standarts is other distros' problem, not Arch's.
Good advice, but PEP8 says 4 spaces per indentation is the recommended style. This is especially important if you start sharing code with other Python programmers.
Grab a copy of the Python source and build the docs (run make html
in the Doc/ subdirectory; do this online just in case you need to install extra stuff to make this work). I use my local copy of the docs quite frequently. Also, you'll be able to dig into the source code for the standard library if you get curious.
>Can you define "low level"? I hear that thrown around a fair amount
With all due respect, if you need to ask that, then this language probably is not for you. Rust is not a teaching language, or a particularly easy language to learn, without prior experience in coding.
Look into Python (the subreddit) (the help subreddit) for learning to program.
To answer your question, you should not learn Rust, and I am only being curt because everyone else in this thread has probably said everything about rust you could understand and more already.
Maybe one day when performance does matter, and a high level language like Python or Java will not cut it, you can come to Rust :)
The best way to develop skills is to just start doing the programming. Picking up some idea and running with it.
I'm a software developer professionally (not game dev) and a lot of time is spent doing research on libraries and references. Think about something that you could make related to something you use often (Check out the Steam API, Irc bots, reddit bots, parsing websites you visit) and just do it. Take it one thing at a time and learn to find and parse documentation quickly.
To elaborate on the 'one thing at a time': In the example of parsing a website, there's a set of things that need to happen in order for you to accomplish it. You need to request the page, inspect it to find out where the content you want is, scrap everything else, and then display the content in some readable way (without html tags, etc).
Pick a language to implement it and then use google to help. If we picked python you'd do something similar to the following queries:
And after finding answers with google you'll be able to cross-reference the official python docs for the methods they used:
This is returned from finding out how to get a web page with python
>import urllib
>urllib.urlopen("http://www.python.org")
Since we're importing urllib for it, you can search google for:
And get anything you need from it.
Real world examples of Python use:
As i could understand it, __new__ is a static method. Please see:
http://docs.python.org/reference/datamodel.html#object.__new__
http://stackoverflow.com/questions/9092072/why-isnt-new-in-python-new-style-classes-a-class-method
http://www.python.org/download/releases/2.2/descrintro/#__new__
For class methods, calling the method on the class implicitly sends the current class as the first argument. An example:
class A(object): @classmethod def met(cls, a): print a
We can call this method on the class passing it only one argument and the class will implicitly be sent as the first argument.
A.met(5)
This works.
But when we override __new__, we have to explicitly send cls received in the overridden __new__ as the first argument. I mean we need to write:
super(A, cls).new(cls, *args, **kwargs)
Had it been a class method, this would have worked:
super(A, cls).new(*args, **kwargs)
because the class on which it were called would have been implicitly passed as first argument since it were a class method. But it doesn't work.
That's why i think its a static method.
Let me know if i am wrong somewhere.
Being included is different from being used. Use is also much harder to measure. One indication toward use patterns is the rate of conversion of existing, complex libraries. Django, Pylons, and Twisted (for example) are not yet Python 3 compatible, despite the passage of PEP 3333, which had even been stable for some time before that. Naturally, not all of Python is web stuff, not at all, and numpy and scipy are both 3.1/3.2 compatible, which is a big deal. It is however pretty disconcerting that some of the biggest open source Python projects are still incompatible.
Keep in mind that Python 3 was released in December 8th, 2008. Ruby 1.9.1, the first "stable" (ahem) release of Ruby 1.9 (which had many similar breaking changes, including all kinds of unicode-supporting changes), came out on January 30th, 2009, and 1.9 adoption among libraries and hosting providers is overwhelming.
Different languages, different issues, and again, use is very hard to measure, so I'm only using libraries as a flawed benchmark.
Because manually iterating over and yielding each element or a sub-iterator is less efficient and less readable and -- more importantly -- it fucks up getting values when the current generator is used as a coroutine.
It makes passing iterables straight through much simpler and less prone to mistakes.
Finally, it makes extracting several yield
statements into a sub-function or method much simpler: move them there and yield from
the newly created function or method.
For what reason did they invent their own syntax for type annotations instead of using Python 3's Function Annotations (PEP 3107)?
That way code written for mypy could have been instantly runnable with standard python.
def hello_(self, name: str) -> str:
I think that's the first time I've seen function annotations in serious use. There's one good reason to keep pushing Python 3 adoption.
http://joelonsoftware.com/articles/Unicode.html
http://www.python.org/dev/peps/pep-0008/
http://www.python.org/dev/peps/pep-0249/
Probably numpy, if this is about scientific computing.
General data structures, algorithms, common protocols.
For a more detailed discussion on tabs vs spaces, check this article out.
>... it can be a good idea to avoid tabs alltogether, because the semantics of tabs are not very well-defined in the computer world, and they can be displayed completely differently on different types of systems and editors. Also, tabs often get destroyed or wrongly converted during copy&paste operations, or when a piece of source code is inserted into a web page or other kind of markup code.
To be clear, private attributes should use a single leading underscore. A double leading underscore invokes name mangling (see PEP8, which recommends restraint when using __name). I think a clear convention is sufficient; "real" private attributes aren't necessary.
> Yes. I am constantly being told about how I should be programming in Java because that is the language that will get me jobs.
I strongly disagree with that assertion. Skilled Python programmers are in high demand: http://www.reddit.com/r/Python/comments/u9q0k/how_not_to_get_a_python_job_a_rant/
> Python is laughed at by everyone I know.
Every language has its haters. Choose language based on how much you like it, and take serious criticisms (ie, actual arguments against it) into account; don't worry about people laughing at you.
> I feel like my code is too concentrated (I only have about five/six py documents for this game) and maybe I did not break things up enough.
So break it up some more. there's no reason you can't just take your existing code and split it up :)
> But I hate that it gives the image that I don't know what I'm doing because it's a "kiddy" language.
Programming languages exist to make code easier to write, and not just for newbies.
http://www.python.org/dev/peps/pep-0020/
There isn't one without brackets, assuming the order of operations of the Python interpreter.
Using every number and every operator once:
import itertools d = ['1.','3.','4.','9.'] o = ['+','-','*','/'] for combination in itertools.product(d,o,d,o,d,o,d): if len(set(combination)) == len(combination): expression = ' '.join(combination) answer = eval(expression) print expression,'=',answer
Using every number once:
import itertools d = ['1.','3.','4.','9.'] o = ['+','-','*','/'] for c in itertools.product(d,o,d,o,d,o,d): numbers = (c[0],c[2],c[4],c[6]) if len(set(numbers)) == len(numbers): expression = ' '.join(c) answer = eval(expression) print expression,'=',answer
None of the expressions result in 27.
The bulk of the work here is done using a function from a combinatorics library that computes the Cartesian product of lists of strings, namely itertools' product(). It could be written in a much more ugly way using many nested for loops, or a lengthy list comprehension.
Looks good. If you don't mind a few comments, perhaps:
Have a look at PEP8. To make you code more readable by python programmers consider changing from tabs to spaces (preferably 4 spaces to one tab).
There seem to be a few extra imports. For example, httplib2 is imported twice and glflags is imported for the FLAGS constant that doesn't appear to be used. I'm not sure you need to import oauth2 (as oath) if you are already importing the tools you need from oauth2client.
You are explicitly importing find from string. You could drop this import and use the .find() method of builtin strings. You could also use the .index() method here, too. This would allow you to replace:
Original:
index = find(task['title'], substr) if index != -1: matches[i] = (tasklistID, task, index) i += 1
With:
if substr in task['title']: matches[i] = (tasklistID, task, task['title'].index(substr))
If you have to use a different language feature, then you're not using first-class functions.
Meanwhile, I think the rationale given in PEP-3104 sums up how broken scoping for nested functions is in Python 2. Just using a different language feature (a workaround, here) is not always elegant — even PEP-227 described rebinding variables in an enclosing scope as "awkward", as far back as 2000. And that's why it's practically useless: sure, you can do it, but in practice you wouldn't.
Every deviation you make from those guidelines will cost you a day off the end of your life. Choose wisely.
But seriously; style guides are there for a reason. Every time you go against this trend you're creating roadblocks to code readability; small roadblocks sure, but they add up quickly.
In python we prefer to use lower_case
identifiers for instance variables and functions. Words are often seperated by underscores, but not always. mixedCase
identifiers aren't used in PEP8 python, but CamelCase
is used for class names.
>- Don't use spaces around the '=' sign when used to indicate a > keyword argument or a default parameter value. > >Yes: > def complex(real, imag=0.0): > return magic(r=real, i=imag) > >No: > def complex(real, imag = 0.0): > return magic(r = real, i = imag)
Damnation for the HEATHEN! Repent ye SINNER, for the LORD commands it so.
From Guidoicus (PEP8:18:22)
>Thou shalt not lie with tabs, as with spaces: it is an abomination.
From Rossums I (PEP8:27:2): >Men committed indecent acts with tabs, and received in themselves the due penalty for their perversion.
PEPs (Python Enhancement Proposals) make the language designed by and for the language users themselves. Unlike Python, Ruby’s language design is done by language designers, not users. Moreover, ruby-dev, the mailing list for it, is written in Japanese.
For god's sake, please indent code properly if you're pasting it on reddit.
Put four spaces before each line so Markdown knows it's code.
1 from pyramid.response import Response 2 from pyramid.view import view_config 3 from pyramid.renderers import render_to_response 4 5 def my_blog(request): 6 return {'project': 'tricky'} 7 8 @view_config(renderer='templates/foo.pt') 9 def foo_blog(request): 10 return {'name': 'tricky'}
and
8 config.add_route('foo_blog', '/blog/{foo}', view='tricky.views.Blog.blog.foo_blog', renderer='tricky:templates/mytemplate.pt')
Also, please take the time to learn about PEP8 to make your code more readable. Don't put spaces after opening and before closing parentheses, do put a space after colons in dictionary literals.
BTW, you had a syntax error in the second code sample. You were missing the comma after the first keyword argument.
Well I dunno, futures seem pretty cool: http://www.python.org/dev/peps/pep-3148/
Also it is supposed to do better GIL management code should run a little faster.
The real problem is finding libraries that are compatible with 3.2...
If you are just trying to help them grow, I would suggest teaching them about computer programming which is fun and can really help them find a career later in life. Python is a great starter language and has a dedicated diversity committee that could recommend some resources. Visit http://www.Python.org, go to the "community" tab, and click on "diversity" for more information on bringing programming to historically underrepresented communities
One of the first things to note is that as a software developer, if you don't know the answer to something, you'll have to google it until you find it. Googling is a required skill for self-directed learning. I should probably stop at this one comment, because you will do better for yourself if I do not feed you more information. However....
Colleges tend to stick with a couple of different languages when taking new students from zero to hero. Both MIT and Standford often use Python as the first language, and I highly recommend /r/learnpython. You can learn all of the various abstract constructs within software using just python. Learn Python the Hard Way is an excellent book to start with. Also, check out: http://www.python.org. Don't get hung up on python 2.x vs python 3.x. Do pick one and go with it (reddit is fond of 3.x, but businesses tend to use 2.x). Also check out IPython: http://ipython.org/install.html.
Much of software is built on top of heavy mathematics. Knuth's books on the Art of Computer Programming will give you everything you need to understand the algorithms and data structures that computer science uses every day.
Linux is the standard for software development. Ideally you have access to a linux box. But if not, then try this stack to get started: vagrant, virtual box and ubuntu.
Good luck.
This is more philosophical than practical, but I'd hope that issues/failures within the default python packaging tools (e.g. pip/setuptools/etc.) would be solved by improving those tools, not abandoning them in favor yet another option. The history of python packaging has been troubled to say the least and the result is a complete mess of legacy packaging approaches baked deeply into various libraries. Suffer through a package which tries to use distribute_setup.py to install itself on a modern system and you'll see what I mean.
Recent efforts to provide precompiled packages (see pip 1.5.x and the wheel package format in particular) are damn promising, along with tools like Travis and Tox for manipulating your environment in programmatic ways. So the general ecosystem is (slowly) improving and making the goals you describe easier.
In the end though, none of this is a reason for you personally to not use conda...I just wish the core tools were simpler and more effective.
Those are all part of python 3. The "type hinting" is called function annotation, and the * param is the symbol for keyword only args (i.e. everything to the right of it is a keyword-only argument).
When teaching people list comprehensions I feel it is important to remind them of readability counts [1]. Complex nested comprehensions quickly becomes unreadable, and although slightly slower, good old fashion for loops are sometimes better.
A list comprehension explanation could benefit from mentioning set and dict comprehensions and generator expressions as they have almost identical syntax and use [2].
From the Python Style Guide (PEP 8):
> Limit all lines to a maximum of 79 characters. > > There are still many devices around that are limited to 80 character > lines; plus, limiting windows to 80 characters makes it possible to have > several windows side-by-side. The default wrapping on such devices > disrupts the visual structure of the code, making it more difficult to > understand. Therefore, please limit all lines to a maximum of 79 > characters. For flowing long blocks of text (docstrings or comments), > limiting the length to 72 characters is recommended.
I don't get how this is different from, say:
def postdef(callback): def decorate(func): return callback(func) return decorate
@postdef(lambda def_: weakref.ref(target, def_)) def x(obj): print("{} is being destroyed".format(obj))
Given the limits of the syntax, this could be more generally accomplished using something like an 'in ... let' syntax, e.g.:
in x = weakref.ref(target, destroy) let: target = something def destroy(obj): print("{} is being destroyed".format(obj))
That is, define a syntax for executing a statement using temporary bindings defined in a scope, sort of like a backwards-"with" statement.
[Edit to add: I appear to have reinvented PEP 3150 with different syntax and semantics. In my idea, the names don't get unbound nor are they private; it's just syntax sugar for executing the statement after the block body.]
If you're writing Python code, you should generally try to follow PEP8. Specifically, you might want to look under the section labeled 'Naming Conventions'.
PEP8 is pretty much the accepted standard coding conventions and style guide for Python.
> But on balance, I often suspect we'd all be better off if it didn't exist.
Python avoided having a ternary for a long time, the dev team ended up pressured into adding it, because the usual replacement hacks were either too brittle or too verbose.
A ternary expression really is useful, even if — like pretty much anything in a language — it can be abused.
I don't mean to stomp on your dreams here, but (as an Android developer myself) I would highly recommend starting out small and working your way up rather than trying to learn everything at once.
Start by learning a language like Python and get used to setting up variables, conditionals, loops, functions, and other basics.
Once you have that down you can move to bigger, more "real world" projects. Right away you will realize that these projects require a huge number of variables to keep track of and a better way to structure your program becomes necessary.
At this point you should read some tutorials and information about Object Oriented Programming (OOP). Python does have OOP capabilities, but I would suggest moving to Java at this point because it is designed for OOP from the ground up.
Once you learn and understand the main aspects of OOP (abstraction, inheritance, polymorphism, encapsulation, etc.) and the syntax of Java, THEN I would recommend installing the Android SDK and getting started with that. You will feel a million times more comfortable; pretty much all the Android developer tutorials and documentation are aimed at this kind of audience and not a total beginner.
You do not need to follow this order by any means; it is technically possible for you to start with Java and the Android stack and learn everything from scratch in this environment. I just think that will be far more challenging and frustrating, and I don't want to turn you off from the learning experience. If you can develop fully-featured Android apps then you will, by proxy, be a full Java developer and have a good deal of programming knowledge.
....
--------------------------------------
Ran 4 tests in 0.110s
OK
Excellent!
P.S.: PEP-8ify...
> Function Names
>
> Function names should be lowercase, with words separated by underscores as necessary to improve readability.
>
> mixedCase
is allowed only in contexts where that's already the prevailing style (e.g. threading.py
), to retain backwards compatibility.
I'm assuming he wrote it in python.
Edit: Yeah, it is. He says it here.
I'm leaving this here for reference:
Yet another suggestion. Use selenium. Surprised no one has mentioned it yet.
Here's a quick example stolen from their docs. It was part of a unit test, but I stripped that out.
from selenium import webdriver from selenium.webdriver.common.keys import Keys self.driver = webdriver.Firefox() driver = self.driver driver.get("http://www.python.org") self.assertIn("Python", driver.title) elem = driver.find_element_by_name("q") elem.send_keys("pycon") assert "No results found." not in driver.page_source elem.send_keys(Keys.RETURN)
See here in the docs for a more detailed explanation of what that does.
It will pop up a window that you can interact with normally, along with monitoring elements and sending events.
If you're on Windows, here's a guide so that you don't have to search for links and the edit options every time:
first run notepad as administrator
In notepad, open C:\windows\system32\drivers\etc\hosts
At the bottom of the file add "127.0.0.1 nlsk.neulion.com" without the quotes.
Go to http://www.python.org/downloads/ and download Python 2.7 and install it.
Go to http://pastebin.com/eJpqRSS8 and scroll down to the bottom where it says "Raw paste data" and copy all of that text and paste it into a new file in notepad.
Save that file as "hockey.py" (make sure it isn't being saved as a .txt) inside the folder that python installed to (I think it is C:\Python27).
Download this https://anonfiles.com/file/772e827c8ad308994ccf2fffd3d0b276 and put the .jar file into the same folder you saved hockey.py and Python was installed to.
Finally, open command prompt and type "cd C:\Python27\", then type "python hockey.py" and follow the prompts and it should open the game in VLC.
Any questions just ask.
If anyone wants to set VLC back up on PC here is a quick guide I wrote:
first run notepad as administrator In notepad, open C:\windows\system32\drivers\etc\hosts At the bottom of the file add "127.0.0.1 nlsk.neulion.com" without the quotes. Go to http://www.python.org/downloads/ and download Python 2.7 and install it.
Go to http://pastebin.com/eJpqRSS8 and scroll down to the bottom where it says "Raw paste data" and copy all of that text and paste it into a new file in notepad. Save that file as "hockey.py" (make sure it isn't being saved as a .txt) inside the folder that python installed to (I think it is C:\Python27).
Download this https://anonfiles.com/file/772e827c8ad308994ccf2fffd3d0b276 and put the .jar file into the same folder you saved hockey.py and Python was installed to.
Finally, open command prompt and type "cd C:\Python27\", then type "python hockey.py" and follow the prompts and it should open the game in VLC.
Any questions just ask.
> I try to be very consistent and precise when I generate code.
Thank you. That makes your code more readable.
> Is there a recommended convention for the correct way to place comments?
There isn't, AFAIK. Personally, I place comments above the code I'm trying to explain.
> In extension, is there any proper way to document code?
Consider reading PEP 257, the docstring conventions. In most of the Python code I've read from other projects, I usually see functions and classes having docstrings:
def func(): """ This is a docstring. """ if a > 0: ...
Some even put tests in docstrings.
> Does 80 characters include the preceeding spaces if the code is indented?
Yes. Some editors (e.g., Notepad++, Sublime Text) have a feature where you set the maximum number of characters per line. You can then either set a colored line marking the boundary, or have the editor change the background color of the text that goes beyond that boundary. (IIRC, Geany should have something like that, but I can't remember which menu has it. I'm at work, so I don't have my Linux box with me.)
Would it not be much easier to just make an agreement between yourselves?
You could make a small script and fire it with cron/task scheduler etc at a set time. This would need to be ran from a 'live' machine so whoever is hosting the script would need to have their PC online at that time.
Easiest way I know is to use something like this. All you need to have it work is Python/PRAW and a way to run it at a set time.
While that's true for many "*nix" tools. The ones you mention have native windows ports.
http://win-bash.sourceforge.net/
http://www.python.org/getit/windows/
No cygwin layer or anything. So if you only use those particular tools, you're totally free to use just windows.
TIL from the comments: PEP 393 exists and is intended to get rid of the UCS-2/UCS-4 issue by making everything look like UCS-4 while doing something more space efficient internally.
You should be fine if you use the latest 2.x version instead of 2.3.5 (that is 2.7.2 i guess, here you can check http://www.python.org/getit/releases/)
However, if you try to use any 3.x version, as 3.0 breaks backwards compatibility, you'll possibly have troubles, see http://www.python.org/dev/peps/pep-3000/#compatibility-and-transition
What dmalikov
said it is. See http://www.python.org/search/hypermail/python-1994q3/0145.html
It is in appropriate places on hackage, see e.g. http://hackage.haskell.org/packages/archive/Crypto/4.2.4/doc/html/src/Codec-Encryption-RSA-NumberTheory.html#expmod
The spec was finally settled this summer and published as PEP 3333. In a nutshell, PEP 3333 clarifies that all data passed to or from the server must be a bytestring (i.e. str
in py2 or bytes
in py3) and that the client is responsible for all encoding/decoding concerns. There's a few wrinkles, but you can read the details in the PEP if you care. See in particular the Unicode Issues section.
On a related note, previous PEP 404: Python Virtual Environments is now PEP 405.
I quit using that type of formatting when I came across advanced string formatting. Not exactly an answer to your question, but worth looking at since the topic is the same. I find the syntax to be more in line with the print keyword to print() function changes brought about in Python 3.
I think he might be referring to something like the path module, but I'm not really sure.
edit: related, rejected PEP-0355
I'm only guessing what Armin was referring to, but <code>PEP-0249</code> clearly has 5 different ways to do bind parameters. Quoting the PEP:
'qmark' Question mark style, e.g. '...WHERE name=?' 'numeric' Numeric, positional style, e.g. '...WHERE name=:1' 'named' Named style, e.g. '...WHERE name=:name' 'format' ANSI C printf format codes, e.g. '...WHERE name=%s' 'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s'
EDIT: If SQLAlchemy is too heavy-weight for your tastes, you might still look at something like <code>dbapiext</code> to solve some of these problems.
Did you know that if you change all those comments to multi-line strings, they'll be attached automatically to your functions, and people can see them in the python shell with help()?
Like this:
def gTitle(): """ Get calendar Title from user Format as raw to allow time and date entry. """ a_Title = ''
It's a really useful feature for libraries, since you can practically work out how to use it in the shell. Check out the Docstring PEP for more info.
In your example, you're trying to find out how a method (.title()) of a built-in type (str) is coded. I would advise you to look at the source code of Python itself.
You can download it here.
Sure enough, you can look at how str is defined and how .title() is coded in the Objects/stringobject.c file in the source code.
You should read PEP 8 and follow it. Good code is self-consistent code.
You omit a lot of context in favor of prose. Why is a 'meta' function like this an instance method? What class does it belong to? What's organism() and why is it a global? Why does the method fail silently when rand_func isn't given? Why 'for k in my_dict.keys()' instead of 'for k in my_dict'?
> (I realize I can do this with zip, if expressions and a lambda, but for blogging purposes I decided to do this in more than one line)
'Exercise for the reader' excuses like this do not make for interesting reading. If you realize you can do this, why not actually give the example?
also on the indent thing, make sure you set your editor to use spaces and not tabs. 4 spaces is the preferred indent, from PEP 8
really, just read through that style guide to get a sense of what well-formed python should look like.
Good god man, those two lines look like they could use a little python zen.
Also, is it really needed to cast x to a string in that second line?
First time poster here, go easy on me. I recently started learning programming after dabbling with web development for a couple of years. Here's a project I took up to teach myself Python. It scrapes episode data from epguides.com and renames selected files automatically by determining what episode and season it is from the current filename, "dexter_s02e01_720p.mkv" for example.
It seems to work pretty well just now. I've renamed about half a TB of TV episodes successfully. I eventually intend on adding undo functionality and an ability to designate your own rename format masks. For example: "<SEASONNUM> - <EPNUM>.<EXT>". Addition of API calls to alternate TV sources might also be on the cards.
The code isn't very tidy just now, probably a bit of an eyesore to some of you pros. I've only spent a couple of nights on it and I wanted to get it out there for some feedback. This is my first big programming project and I'd really appreciate any feedback on how I could improve the application or implementation.
Edit 1: Extract somewhere and run "python pyShowRename.py" to load it. You'll need to have Python installed.
Edit 2: There's currently no working "undo" functionality so be careful with batch renames!
Edit 3: Downvotes!? How does that work?
Python - Computer language for everybody: Easy to learn/read/write and Elegant design.
Reddit recommend you to learn Python -> https://www.reddit.com/r/learnprogramming/wiki/faq
Style is a personal choice, but in Python we have PEP-8 to help keep everyone's python code consistent. There's no particular advantage to any particular code style. However, if we all use the same style (such as PEP-8), it's a lot easier for us all to share code and read each other's code.
So first off, good job on completing your final project. I hope you enjoyed working on it.
as-is, this stands as borderline unreadable and completely unmaintainable.
Some code criticisms:
somefunc.__doc__
to see the docstring. For instance, what on earth is change() doing??if func(arg) == True:
is the same as if func(arg):
.if __name__ == '__main__':...
Some style criticisms which might not necessarily apply to you:
Basically... unless you have been assigned a style to use, follow PEP8 as much as you can.
I admit that my browser (or dropbox) might not be rendering the formatting as you intended.
It would seem you're reading material that's written for Python 3.x, but you're using Python 2.x. Refer to PEP 3114: in Python 2.x your iterator needs to implement a next()
method.
Every project should have a "one true style guide". With so many different preferences out there, it's hard to guess how the people in charge of a certain project want you to write your code.
The JavaScript language will never have a PEP 8.
There is absolutely no need to install Linux in order to learn Java - you can download and install the JDK for Windows from http://www.oracle.com/technetwork/java/javase/downloads/index.html.
However, you may be better advised to start with something simpler, such as Python. Books and other resources are in the FAQ.
> if semi=="Y" or "y":
Precedence rules turn this into if (semi=="Y") or ("y"):
which is always true.
Also, take a look at PEP8, especially this section.
Python since 3.2 chooses what representation to use based on the highest code point in the string. I think this is a better idea for internal string handling than UTF-8 because it keeps everything fixed width. The thing is, for strings, fixed width is always more performant than variable width. Indexing a string does not require scanning it, and scanning a string does not require extra processing.
And, while we're busy deciding how we should represent strings in the future, let's talk about null terminators. Can we please stop using these relics of a bygone era? I seriously do not see the reason why just storing the length of a string alongside the data is so hard. It's safer, for many reasons.
As an experienced C++ programmer and instructor, I'd really suggest you learn another language (I recommend Python) before embarking on C++ - it is not a great language for beginners.
I don't know. CAN you?
Seriously, though... You need to have python installed on your computer for it to work. Python code gets translated into code for your machine/os when it runs. So you need to install python for this to work. There could be some bejiggering to tweak it to work on your machine. There could also not be.
I would use the property function over getattr and setattr:
http://www.python.org/download/releases/2.2/descrintro/#property
If you're only making a read-only property, you can use a decorator for this, which simplifies the code:
@property def your_property(self): return whatever
C I MUST ADMIT, I STILL HAVE SOME B 000100 C AD HABITS I PICKED UP FROM THOSE 000200 C OLD DAYS, BY AND LARGE I BELIEVE 000300 C I HAVE OVERCOME MOST OF THE WORST 000400 C ONES. 000500
Because Python is Python and we stick to style guides not whatever the author of your syntax highlighter felt like :) You've probably read it but just in case you haven't: stick to PEP8 - it will stop the people reading your code from going insane.
The fundamental problem is that Unix treats filenames as just strings of bytes. Only the slash and null are not allowed. So if possible, your program should do the same. If you have to display the filenames or allow user input in unicode, I'm not sure what the best approach is. I usually ignore files with non-decodeable filenames. Also interesting is what they do in Python 3.1 (also relevant is this mail by Markus Kuhn).
I have a different suggestion: Print PEP 8. Print PEP 20. Read them SLOWLY then read them AGAIN. Read PEP 20 and meditate on each line asking it why does it exists.
Next, write some code and 1. Assume it sucks. 2. Figure out why it sucks. (read the PEPs again if you need some reminding). 3 Make it suck less.
The end product will show you the end product but it will do very little to teach you how to get to the end product. Just like cooking. You can look and taste things produced by great cooks but any attempt to imitate the outer final object is a recipe in frustration.
Make peace in your heart and listen to the Will of the Code. It will teach you the discipline you need.
Good general advice, esp about evaluating a framework with a concrete problem.
I'm very experienced with PHP, moderately experienced with Py/Django, and have briefly touched Ruby/Rails. I think those three languages are ones to focus on and you won't be going too wrong with any of them.
Though my favourite is Py/Dj.
Some points:
PHP
Python/Django
Ruby/Rails (shakier on these)
I always recommend python as a first language. It's open source (free), runs on many platforms, has a huge active community, has extensive documentation and tutorials you can find on the home page.
Since you're new, I would recommend sticking with the newer version 3 but others might have differing opinions.
Python will probably not be what you use most in your career but it is very good to get you started.
I believe list comprehensions came in to replace map or while loops that are purely to populate a list while only doing a small task, as it's meant to look shorter while not looking messier. PEP 202
You can do a hell of a lot more with reduce than sum, and sum is only there because its a nice shortcut to something people might commonly use.
>Is there a library or reference list of some sort listing different codes and functions and what each one does?
If I understand correctly, you're looking for documentation? You could start with python documentation from their main website here. Just choose the appropriate version that you have installed on your machine.
As for learning Python interactively... Python is a scripting language that interprets rather than compiles, something that most other languages do. That is as interactive as it gets, in my opinion.
Another suggestion is to pick up a book that's written for children to learn Python. It is sufficiently peppered with activities to get your hands dirty. Not endorsing anything but you can check this out.
I'll add my two cents in. I enjoy programming (like software design). I find that it helps a lot because it forces me to think through problems in an interesting way, and it makes me feel very proud of myself and accomplished when I finally do work through the problem. Its also fun when i run the program and see that it works. Of course, I'm sure it's a similar type of idea to other people who have mentioned they do puzzles.
If you're interested, try Python. Its what I started on, and I've found tends to be more gentle to beginners who have no experience in programming than other languages (like C++ or Java). Feel free to contact me for help!
File "Build the Universe.py", line 126 SyntaxError: Non-ASCII character '\xe2' in file Build the Universe.py on line 126, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details