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.



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.


Standard arithmetic operators are used in Python:

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

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

In addition to bitwise logic operators:

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

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:

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.




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 + \

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

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


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


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

if expression : 
elif expression : 
else : 

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]


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


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

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

class MyClass(Mixin2, Mixin1):

obj = MyClass()



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


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



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.


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


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





* 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]


  1. Python - Basic Operators:
  2. Python - Bitwise Operators:
  3. Python basic syntax:
  4. Passing Command line arguments to Python:
  5. TypeError - Can't convert 'int' object to str implicitly:
  6. What is a mixin, and why are they useful?:
  7. Reddit - What are the top 10 built-in Python modules that a new Python programmer needs to know in detail? (self.Python):
  8. Top 10 Python libraries of 2015:
  9. Top 10 Python libraries of 2016:
  10. What are the top 10 most useful and influential Python libraries and frameworks?:
  11. Python: 50 modules for all needs:
  12. How to write a Python module?:
  13. Importing Modules Using from module import:
  14. Inno Setup: (free installer for Windows programs)
  15. Esky: | DOCS | SRC (pip install esky)
  16. How to remotely update Python applications:
  17. Restarting a self-updating python script:
  18. Python code obfuscation:
  19. Python Code Obfuscator"
  20. How to obfuscate Python source code:
  21. How to Obfuscate Code in Python - A Thought Experiment:
  22. How to obfuscate Python code effectively?:
  23. Introduction to Jython Application Development Using NetBeans IDE:
  24. Introduction to Python Application Development Using NetBeans IDE:
  25. The IPython Notebook is now known as the Jupyter Notebook:
  26. DataCamp - Jupyter Notebooks (Python for Data Science):
  27. Parsing XML (or xHTML) in Python with lxml:
  28. Numpy Guide for People In a Hurry:
  29. TensorFlow API Docs - All symbols:
  30. Top 15 Python Libraries for Data Science in 2017:
  31. HiPlot -- High-dimensional interactive plots made easy:
  32. HiPlot -- Interactive Visualization Tool by Facebook:
  33. Using Relational Databases with Python:
  34. Managing Records in Python with "record" .vs. "namedtuple":
  35. Cryptography options in Python:
  36. Running App Engine Applications on Django:
  37. Should I learn Flask or Django?:
  38. Abandoning Flask for FastAPI:
  39. Pyglet Tutorial:
  40. Python GUI Examples (Tkinter Tutorial):
  41. Python for Windows:
  42. How do I create a multiline Python string with inline variables?:
  43. Ternary Operators in Python:
  44. Ternary Operator in Python?:
  45. Ternary Operator in Python:
  46. 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:
  48. Python - Check if a list is empty or not:
  49. Python - Check if string is empty or blank or contain spaces only:
  50. What is Null (None) in Python
  51. Serving Files with Python's SimpleHTTPServer module:
  52. Simple Python HTTP(S) Server — Example:
  53. Exploring HTTPS With Python:
  54. Python HTTP to HTTPS redirector:
  55. Python | os.environ object:
  56. Python requests call with URL using parameters:
  57. python parsing file json:
  58. Packt -- Python for Finance (BOOK): | SRC
  59. Packt -- Hands-On Python for Finance (BOOK): | SRC
  60. Packt -- Mastering Python for Finance (BOOK): | SRC
  61. Python -
  62. Python - lib:
  63. How to emit message from python server to javascript client in python-socketio?:
  64. Implementation of (HTML5) WebSocket spec using Socket-IO in Python:
  65. Learn Socket.IO with Python and JavaScript in 90 Minutes!:
  66. Python 3.0 Release:
  67. Install Python and Django with XAMPP on Windows 7:
  68. Running Python scripts with XAMPP:

See Also

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