Sunday, June 8, 2014
On 9:12 PM by Unknown No comments
Here's a syntax cheatsheet for python programmers!
Yes, we know how you love cheat sheets, and for a complex language like python, cheatsheets are a big boon! So to add to your collection, here we bring to you a cheat sheet with list of syntax used in python. Happy coding!
Courtesy: Himanshu Teotia
| Language Category: Object Oriented, Dynamically typed, Has anonymous functions | |
| Various | |
| indentation | block (grouping statements, especially when statements are not expressions) |
| \ | breaking lines (useful when end-of-line and/or indentation has a special meaning) |
| # | commenting (until end of line) |
| < > <= >= | comparison |
| min / max | comparison (min / max (binary or more)) |
| cmp | comparison (returns 3 values (i.e. inferior, equal or superior)) |
| class X: """... """ def x(): """... """ | documentation comment |
| Err:510 | equality / inequality (deep) |
| Err:510 | equality / inequality (deep) |
| is / is not | equality / inequality (shallow) |
| gc.collect() | force garbage collection |
| ( ... ) | grouping expressions |
| __file__ | information about the current line and file |
| eval | runtime evaluation |
| exec | runtime evaluation |
| case-sensitive | tokens (case-sensitivity (keywords, variable identifiers...)) |
| [_a-zA-Z][_a-zA-Z0-9]* | tokens (variable identifier regexp) |
| CamelCase for classes, underscores for methods | tokens (what is the standard way for scrunching together multiple words) |
| = | variable assignment or declaration (both) |
| global v1, v2 | variable assignment or declaration (declaration) |
| Functions | |
| functools.partial(f, a) | partial application (in the examples below, a normal call is "f(a,b)") (give the first argument) |
| lambda a, b: ... | anonymous function |
| f(a,b,...) | function call |
| f() | function call (with no parameter) |
| __getattr__ | function called when a function is not defined (in dynamic languages) |
| def f(para1, para2, ...): ... | function definition |
| return | function return value (breaks the control flow) |
| inspect.stack()[1] | runtime inspecting the caller information |
| Control Flow | |
| continue / break | breaking control flow (continue / break) |
| return | breaking control flow (returning a value) |
| try: a except exn: ... | exception (catching) |
| finally | exception (cleanup: code executed before leaving) |
| raise | exception (throwing) |
| if c: ... | if_then |
| b1 if c else b2 | if_then_else |
| if c: b1 elif c2: b2 else: b3 | if_then_else |
| for i in xrange(10, 0, -1) | loop (for each value in a numeric range, 1 decrement) |
| for i in xrange(1, 11) | loop (for each value in a numeric range, 1 increment (see also the entries about ranges)) |
| for i in xrange(1, 11, 2) | loop (for each value in a numeric range, free increment) |
| while c: ... | loop (while condition do something) |
| ; | sequence |
| end-of-line | sequence |
| Types | |
| t(e) | cast (computed conversion (calls an internal or a user-defined function)) |
| n = t | declaration |
| Object Oriented & Reflexivity | |
| super(Class, self).meth(args) | accessing parent method |
| class | class declaration |
| first parameter | current instance |
| __class__ | get the type/class corresponding to an object/instance/value |
| hasattr(obj, "meth") | has the method |
| class child(parent): | inheritance |
| del, __del__ | manually call an object's destructor |
| object.method(para) | method invocation |
| object.method() | method invocation (with no parameter) |
| dir | methods available |
| copy.copy(o) | object cloning |
| class_name(...) | object creation |
| isinstance | testing class membership |
| Package, Module | |
| automatically done based on the file name | declare |
| __all__ = [ ... ] | declare (selective export) |
| from p import * | import (everything into current namespace) |
| import p | import (package (ie. load the package)) |
| from p import name1, name2, ... | import (selectively) |
| 0 | package scope |
| Strings | |
| s[n] | accessing n-th character |
| chr | ascii to character |
| ord | character to ascii |
| str, `e`, repr | convert something to a string (see also string interpolation) |
| * | duplicate n times |
| s[n:m+1] | extract a substring |
| index | locate a substring |
| find | locate a substring |
| rindex | locate a substring (starting at the end) |
| rfind | locate a substring (starting at the end) |
| '''...''', """...""" | multi-line |
| pickle.dump | serialize (marshalling) |
| simple print (on any objects) | |
| print e, | simple print (on any objects) |
| % | sprintf-like |
| 0 | string concatenation |
| Err:510 | string equality & inequality |
| Err:510 | string equality & inequality |
| len | string size |
| "\n" | strings (end-of-line (without writing the real CR or LF character)) |
| "... %(v)s ..." % vars() | strings (with interpolation of variables) |
| '...' | strings (with no interpolation of variables) |
| "..." | strings (with no interpolation of variables) |
| '''...''' | strings (with no interpolation of variables) |
| """...""" | strings (with no interpolation of variables) |
| str | type name |
| pickle.load | unserialize (un-marshalling) |
| upper / lower | upper / lower case character |
| upper / lower / capitalize | uppercase / lowercase / capitalized string |
| Booleans | |
| False | false value |
| None | false value |
| 0 | false value |
| "" | false value |
| () | false value |
| [] | false value |
| {} | false value |
| not | logical not |
| or / and | logical or / and (short circuit) |
| True | true value |
| anything not false | true value |
| bool | type name |
| Bags and Lists | |
| zip(*l) | 2 lists from a list of couples |
| a.insert(i, e) | adding an element at index (side-effect) |
| append | adding an element at the end (side-effect) |
| l[1:] | all but the first element |
| reduce | f(... f(f(init, e1), e2) ..., en) |
| index | find an element |
| for v in l: ... | for each element do something |
| pop | get the last element and remove it |
| in | is an element in the list |
| any | is the predicate true for an element |
| all | is the predicate true for every element |
| enumerate(l) | iterate with index |
| s.join(l) | join a list of strings in a string using a glue string |
| filter | keep elements (matching) |
| [ x for x in l if p(x) ] | keep elements (matching) |
| a[-1] | last element |
| 0 | list concatenation |
| [ a, b, c ] | list constructor |
| zip | list of couples from 2 lists |
| list | list out of a bag |
| len | list size |
| a[i] | list/array indexing |
| set | remove duplicates |
| reverse | reverse |
| reversed | reverse |
| l[::-1] | reverse |
| min / max | smallest / biggest element |
| sort | sort |
| sorted | sort |
| map | transform a list (or bag) in another one |
| [ f(x) for x in l ] | transform a list (or bag) in another one |
| map | transform two lists in parallel |
| list | type name |
| Various Data Types | |
| a, | computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple) |
| tuple([a]) | computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (1-uple) |
| () | computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (empty tuple) |
| *t | computable tuple (these are a kind of immutable lists playing a special role in parameter passing) (using a tuple for a function call) |
| h.get(k, returned_value_when_k_unfound) | dictionary (access: read) |
| h[k] | dictionary (access: read/write) |
| { a: b, c: d } | dictionary (constructor) |
| has_key | dictionary (has the key ?) |
| k in h | dictionary (has the key ?) |
| k not in h | dictionary (has the key ?) |
| keys | dictionary (list of keys) |
| values | dictionary (list of values) |
| update | dictionary (merge) |
| del h[k] | dictionary (remove by key) |
| dict | dictionary (type name) |
| or | optional value (null coalescing) |
| None | optional value (null value) |
| v | optional value (value) |
| range | range (inclusive .. exclusive) |
| 0 | record (selector) |
| a, b, c | tuple constructor |
| tuple | tuple type |
| Mathematics | |
| + / - / * / / | addition / subtraction / multiplication / division |
| & / | / ^ | bitwise operators (and / or / xor) |
| ~ | bitwise operators (bitwise inversion) |
| << / >> | bitwise operators (left shift / right shift / unsigned right shift) |
| divmod | euclidian division (both quotient and modulo) |
| ** | exponentiation (power) |
| pow | exponentiation (power) |
| log10 | logarithm (base 10) |
| log(val, 2) | logarithm (base 2) |
| log | logarithm (base e) |
| % | modulo (modulo of -3 / 2 is 1) |
| -0 | negation |
| 1000., 1E3 | numbers syntax (floating point) |
| 07, 0xf | numbers syntax (integers in base 2, octal and hexadecimal) |
| 1000 | numbers syntax (integers) |
| mathematical | operator priorities and associativities (addition vs multiplication) |
| mathematical | operator priorities and associativities (exponentiation vs negation (is -3^2 equal to 9 or -9)) |
| random | random (random number) |
| random.seed | random (seed the pseudo random generator) |
| sqrt / exp / abs | square root / e-exponential / absolute value |
| sin / cos / tan | trigonometry (basic) |
| asin / acos / atan | trigonometry (inverse) |
| int / round / floor / ceil | truncate / round / floor / ceil |
| float, decimal.Decimal | type name (floating point) |
| int, long | type name (integers) |
| Threads | |
| OtherThread.join() | Joining Another Thread (Suspending a thread until another thread completes) |
| class class_name(threading.Thread) {[override run method] } | thread definition |
Courtesy: Himanshu Teotia
Subscribe to:
Post Comments (Atom)
Search
Popular Posts
-
Looking for a free ebooks on some topic? Your search ends here with these websites.. When looking for free ebooks, there are many reso...
-
This is the age of connectivity. We randomly switch from smartphone to tablet to computer many times every single day, so much so that some...
-
Hi friends some of the viewers had messaged me to give hacking books so that they can learn every thing offline.So here i am providing with...
-
Carrying around an actual computer is now possible since we have USB sticks that you can use to store all the basic utilities you need and ...
-
The following keyloggers are handy tools for hacking/surveillance. Keylogger is basically a surveillance software that has the capabi...
-
The importance of encryption tools lies in one simple fact. Prevention is better than cure. File encryption is of paramount importance...
-
Some would say that hacking has been simplified by the array of hacking tools that are available nowadays. While that remains a topic for a...
-
Hacking tools are available aplenty. Top hackers in the world today recommend hacking tools made for Linux and Windows operating systems. I...
-
Did you know you could use HTML to hack a website? Here's how to do it! Yes folks, you can use HTML to hack a website....
-
Comfort in the source code editor is very important for a programmer to be productive. When it comes to editing source codes, every pr...
Copy Rights 2014 Himanshu_Teotia. Powered by Blogger.
0 comments:
Post a Comment