Python

From BC$ MobileTV Wiki
Jump to: navigation, search

Python: A lightweight interpreted scripting languagePython is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to TCL, Perl, PHP, Ruby, Scheme or Java.

Specifications

Language

Some of Python's key distinguishing features include:

   * very clear, readable syntax
   * strong introspection capabilities
   * intuitive object orientation
   * natural expression of procedural code
   * full modularity, supporting hierarchical packages
   * exception-based error handling
   * very high level dynamic data types
   * extensive standard libraries and third party modules for virtually every task
   * extensions and modules easily written in C, C++ (or Java for Jython, or .NET languages for IronPython)
   * embeddable within applications as a scripting interface

Python's core language syntax differs from a number of comparable programming languages in that it does not require line-ending indicators and instead relies on newline as a marker of logical terminations. In addition, where other curly braces "{ stuff }" or other indicators are used for code or logic blocks, indentation (i.e. tabs or spaces bringing one line of code below another) are used to indicate the logical flow of Python programs. For these reasons, the use of whitespace in Python is considered very important to learn and constantly keep in mind while programming, with an emphasis on conciseness and clarity.

Operators

Standard arithmetic operators are used in Python:

OperatorDescription
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus (method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction

The standard assignment operators you'd expect are there:

OperatorDescription
= %= /= //= -= += *= **= Assignment operators

In addition to bitwise logic operators:

OperatorDescription
>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators

And also a few Python-specific operators/shorthands:

OperatorDescription
is is not Identity operators
in not in Membership operators

Lastly, the standard logic operators you'd expect are also in Python and evaluate last:

OperatorDescription
not or and Logical operators

The order in which the operators are listed here (from top to bottom, left to right) also indicates the operator precedence, so exponentiation "**" takes first precedence, down to the logic "not", "or" "and".

[1] [2]

Reserved/native keywords

The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. All the Python keywords contain lowercase letters only.

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

[3]

Variables

There is no typing requirement in Python (though it is possible with OOP frameworks), so you simply declare a variable and assign it a value:

message = 'Hello World'

Or for numerical calculations:

There is also no strict preference on the casing of variables. You could use camelCase, or [ underscore_casing] and others preferred naming conventions.

Variable declarations can be broken down to multiple lines if necessary:

total = item_one + \
        item_two + \
        item_three + \
        item_four

Statements contained within the [], {}, or () brackets do not need to use Python's "line-continuation" character:

days = ['Monday', 'Tuesday', 'Wednesday',
       'Thursday', 'Friday']

Text

Variables that would be considered Strings in other languages are just considered text characters or "blocks of text".

You can set a word variable as follows using opening and closing single-quotes ('):

word = 'word'

Alternatively, single-line longer text content can (but does not need to) use opening and closing double-quotes ("):

sentence = "This is a sentence."

Multi-line content should use the Python-unique opening and closing triple-quote syntax ("""):

paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""

Suites

Code blocks of IF/ELSE statements that evaluate how a program executes based on particular condition(s) are called Suites.

if expression : 
  suite
elif expression : 
  suite 
else : 
  suite

User Input

You can prompt the user for input at the command-line/terminal using the following:

raw_input("\n\nPress the enter key.")

Where of course each "\n" indicates a newline, typically done to make the prompt instructions clear to the user (spacing out and bringing the keyboard cursor down two spaces from the command-line run line from which the Python program was called to begin with). [4]

Output

Messages or data can be output to the console window (or if using a CGI/Web library, to a browser) using:

print 'message or data to output goes here'

You can easily combine text and text (concatenate strings as it is referred to in other languages):

x = 'Hello'
y = 'World'
print('I just wanted to say: ' + x + y)

And just as easily combine text and numbers, but need to convert to String first using str native function or else will suffer a TypeError[5]:

x = 1
y = 2
print('Sum: ' + str(x + y))

NOTE that while Python 2.x and earlier supported use of print without opening and closing brackets (as a keyword not function) in Python 3.x you must put all printed values within opening and closing brackets, similar to a function/method call with one big "output" parameter representing the values being output to the screen.

Comments

Comments use either this format for multi-line, single-line, or end-of-line comments:

# small comments go here

Python 2.x supported the Java/C style syntax, but it has been phased out in Python 3.x:

/**
 * Multi-line comments 
 */

Mixin

A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:

  1. You want to provide a lot of optional features for a class.
  2. You want to use one particular feature in a lot of different classes.
class Mixin1(object):
   def test(self):
       print("Mixin1")

class Mixin2(object):
   def test(self):
       print("Mixin2")

class MyClass(Mixin2, Mixin1):
   pass

obj = MyClass()
obj.test()

[6]

Libraries

Writing (rolling) your own library is one of the main barriers to productivity in Python. Once you've "crossed" this barrier, you will have a much better handle on the language. Libraries in Python are actually referred to as Modules.

A module is any file containing Python definitions and statements, where the filename becomes the module name with the suffix .py appended. To group many .py files together to provide a broader set of capabilities, put them in a folder. Any folder with an __init__.py is considered a module by python and you can call folders of modules a package.

A package is a way of structuring Python’s module namespace by using "dotted module names". For example, the module name A.B' designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of "multi-module packages" like BeautifulSoup, NumPy or the Python Imaging Library from having to worry about each other's (and the rest of the world's) module names, avoiding variable collisions or naming conflicts.


Imports

Importing is key to extending the base capabilities of the language, and is done as follows:

from package import module

The "from package" section can be ommitted, for example:

import requests

Package names can be simple, as in this example to work with WSGI web framework "wekzeug":

from werkzeug import BaseRequest, AcceptMixin

Or dotted and more specific, as in this example to include Django's "Models" ORM lib for working with databases:

from django.db import models

This could go for several levels if needed to ensure specificity and no namespace collision, for example to include the external Cryptography hash classes, you could use:

from cryptography.hazmat.primitives import hashes

[13]


PIP

Recrusive acronym PIP Installs Packages (PIP) is the Python package manager for bringing in useful third party libraries and managing dependencies within your own Python code.

If you've written a library/module that you think would be useful to the broader community, you can submit it for consideration for inclusion on the Python package index. If it really is found to be useful by the broader community, then it may get featured on the Useful Modules section which would garner more significant attention and traffic.


Auto-updating

[14] [15] [16] [17]


Obsfucation

[18] [19] [20] [21] [22]


Tools


Resources

Libs


Tutorials

* Check if word is in a String: http://stackoverflow.com/questions/5319922/python-check-if-word-is-in-a-string

[43] [44] [45] [46] [47] [48] [49] [50]

[51] [52] [53] [54]

[55] [56]

[61] [62] [63] [64] [65]


External Links

[67] [68]


References

  1. Python - Basic Operators: http://www.tutorialspoint.com/python/python_basic_operators.htm
  2. Python - Bitwise Operators: http://www.tutorialspoint.com/python/bitwise_operators_example.htm
  3. Python basic syntax: http://www.tutorialspoint.com/python/python_basic_syntax.htm
  4. Passing Command line arguments to Python: https://unix.stackexchange.com/questions/321107/passing-command-line-arguments-to-python#321109
  5. TypeError - Can't convert 'int' object to str implicitly: http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly#13654181
  6. What is a mixin, and why are they useful?: http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful#547714
  7. Reddit - What are the top 10 built-in Python modules that a new Python programmer needs to know in detail? (self.Python): http://www.reddit.com/r/Python/comments/28yo37/what_are_the_top_10_builtin_python_modules_that_a/
  8. Top 10 Python libraries of 2015: http://tryolabs.com/blog/2015/12/15/top-10-python-libraries-of-2015/
  9. Top 10 Python libraries of 2016: http://tryolabs.com/blog/2016/12/20/top-10-python-libraries-of-2016/
  10. What are the top 10 most useful and influential Python libraries and frameworks?: http://www.quora.com/What-are-the-top-10-most-useful-and-influential-Python-libraries-and-frameworks
  11. Python: 50 modules for all needs: http://www.catswhocode.com/blog/python-50-modules-for-all-needs
  12. How to write a Python module?: http://stackoverflow.com/questions/15746675/how-to-write-a-python-module
  13. Importing Modules Using from module import: http://www.diveintopython.net/object_oriented_framework/importing_modules.html
  14. Inno Setup: https://jrsoftware.org/isinfo.php (free installer for Windows programs)
  15. Esky: https://pypi.org/project/esky/ | DOCS | SRC (pip install esky)
  16. How to remotely update Python applications: https://stackoverflow.com/questions/6932389/how-to-remotely-update-python-applications
  17. Restarting a self-updating python script: https://stackoverflow.com/questions/1750757/restarting-a-self-updating-python-script
  18. Python code obfuscation: https://medium.com/analytics-vidhya/python-code-obfuscation-a2779af857bb
  19. Python Code Obfuscator" https://github.com/brandonasuncion/Python-Code-Obfuscator
  20. How to obfuscate Python source code: https://laptrinhx.com/how-to-obfuscate-python-source-code-950946278/
  21. How to Obfuscate Code in Python - A Thought Experiment: https://therenegadecoder.com/code/how-to-obfuscate-code-in-python/
  22. How to obfuscate Python code effectively?: https://stackoverflow.com/questions/3344115/how-to-obfuscate-python-code-effectively
  23. Introduction to Jython Application Development Using NetBeans IDE: http://netbeans.org/kb/docs/python/jython-quickstart.html
  24. Introduction to Python Application Development Using NetBeans IDE: http://netbeans.org/kb/docs/python/python-quickstart.html
  25. The IPython Notebook is now known as the Jupyter Notebook: http://ipython.org/notebook.html
  26. DataCamp - Jupyter Notebooks (Python for Data Science): https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook
  27. Parsing XML (or xHTML) in Python with lxml: http://lxml.de/parsing.html
  28. Numpy Guide for People In a Hurry: https://towardsdatascience.com/numpy-guide-for-people-in-a-hurry-22232699259f
  29. TensorFlow API Docs - All symbols: http://www.tensorflow.org/api_docs/python/
  30. Top 15 Python Libraries for Data Science in 2017: https://medium.com/activewizards-machine-learning-company/top-15-python-libraries-for-data-science-in-in-2017-ab61b4f9b4a7
  31. HiPlot -- High-dimensional interactive plots made easy: https://ai.facebook.com/blog/hiplot-high-dimensional-interactive-plots-made-easy/
  32. HiPlot -- Interactive Visualization Tool by Facebook: https://towardsdatascience.com/hiplot-interactive-visualization-tool-by-facebook-f83aea1b639a
  33. Using Relational Databases with Python: http://halfcooked.com/presentations/osdc2006/python_databases.html
  34. Managing Records in Python with "record" .vs. "namedtuple": http://www.artima.com/weblogs/viewpost.jsp?thread=236637
  35. Cryptography options in Python: http://docs.python-guide.org/en/latest/scenarios/crypto/
  36. Running App Engine Applications on Django: http://code.google.com/appengine/articles/pure_django.html
  37. Should I learn Flask or Django?: http://www.quora.com/Should-I-learn-Flask-or-Django
  38. Abandoning Flask for FastAPI: https://python.plainenglish.io/abandoning-flask-for-fastapi-20105948b062
  39. Pyglet Tutorial: http://steveasleep.com/pyglettutorial.html
  40. Python GUI Examples (Tkinter Tutorial): https://dzone.com/articles/python-gui-examples-tkinter-tutorial-like-geeks
  41. Python for Windows: http://www.imladris.com/Scripts/PythonForWindows.html
  42. How do I create a multiline Python string with inline variables?: https://exceptionshub.com/how-do-i-create-a-multiline-python-string-with-inline-variables.html
  43. Ternary Operators in Python: https://book.pythontips.com/en/latest/ternary_operators.html
  44. Ternary Operator in Python?: https://www.tutorialspoint.com/ternary-operator-in-python
  45. Ternary Operator in Python: https://www.geeksforgeeks.org/ternary-operator-in-python/
  46. What is the most Pythonic way to provide a fall-back value in an assignment?: https://stackoverflow.com/questions/768175/what-is-the-most-pythonic-way-to-provide-a-fall-back-value-in-an-assignment
  47. Test multiple conditions with a Python if statement -- and & or explained: https://kodify.net/python/if-else/if-conditions/
  48. Python - Check if a list is empty or not: https://thispointer.com/python-check-if-a-list-or-list-of-lists-is-empty-or-not/
  49. Python - Check if string is empty or blank or contain spaces only: https://thispointer.com/python-check-if-string-is-empty-or-blank-or-contain-spaces-only/
  50. What is Null (None) in Python https://www.pythonpool.com/python-null/
  51. Serving Files with Python's SimpleHTTPServer module: https://stackabuse.com/serving-files-with-pythons-simplehttpserver-module/
  52. Simple Python HTTP(S) Server — Example: https://blog.anvileight.com/posts/simple-python-http-server/
  53. Exploring HTTPS With Python: https://realpython.com/python-https/
  54. Python HTTP to HTTPS redirector: https://elifulkerson.com/projects/http-https-redirect.php
  55. Python | os.environ object: https://www.geeksforgeeks.org/python-os-environ-object/
  56. Python requests call with URL using parameters: https://stackoverflow.com/questions/38476648/python-requests-call-with-url-using-parameters
  57. python parsing file json: http://stackoverflow.com/questions/2835559/python-parsing-file-json
  58. Packt -- Python for Finance (BOOK): https://www.packtpub.com/big-data-and-business-intelligence/python-finance-second-edition | SRC
  59. Packt -- Hands-On Python for Finance (BOOK): https://www.packtpub.com/big-data-and-business-intelligence/hands-python-finance | SRC
  60. Packt -- Mastering Python for Finance (BOOK): https://www.packtpub.com/big-data-and-business-intelligence/mastering-python-finance | SRC
  61. Python - Socket.io: https://python-socketio.readthedocs.io/en/latest/
  62. Python - Socket.io lib: https://github.com/miguelgrinberg/python-socketio
  63. How to emit message from python server to javascript client in python-socketio?: https://stackoverflow.com/questions/52788198/how-to-emit-message-from-python-server-to-javascript-client-in-python-socketio
  64. Implementation of (HTML5) WebSocket spec using Socket-IO in Python: https://www.includehelp.com/python/implementation-of-websocket-using-socket-io-in-python.aspx
  65. Learn Socket.IO with Python and JavaScript in 90 Minutes!: https://blog.miguelgrinberg.com/post/learn-socket-io-with-python-and-javascript-in-90-minutes
  66. Python 3.0 Release: https://www.python.org/download/releases/3.0/
  67. Install Python and Django with XAMPP on Windows 7: http://www.leonardaustin.com/technical/install-python-and-django-with-xampp-on-windows-7
  68. Running Python scripts with XAMPP: https://stackoverflow.com/questions/42704846/running-python-scripts-with-xampp

See Also

LAMP | PHP | Perl | Batch | Shell | Google | R