Skip to main content

Python Facts


Python Facts
Python Facts

Python is a WYSIWYG language--what you see is what you get because the way code looks in the way it runs, regardless of who coded it.

Python2 is backward compatible; whereas Python3 is backward INCOMPATIBLE.
Python supports OOPs concepts. But, in python, both private and protected modes are having same authority. This is the only limitation in python becoming complete OOP language.
Python interpreter generates byte-code, so the python applications are platform-independent.
Python runs faster than java, but slower than C language.
Python was written in C language.
Pre/Post increment/decrement like x++,x--,--x,++x, are INVALID in python
Compound operations such as +=,-=,*=,/= are VALID in Python
Python is case-sensitive i.e., variable “work” is different from variable “Work”, or “WORK
Using underscores (eg:price_at_opening) and Camel-casing (eg:PriceAtOpening)is VALID
Multiple Assignments are VALID in python.
Ex: x=y=z=1
Parallel assignment (or unpacking) is POSSIBLE in python
Eg: a,b=1,2
(x,y,z)=1,2,3
But,(x,y,z)=12 is not possible.
In python 2, Print is a statement. In python 3, print is a function.
To use print() function of python 3 in python2, place this statement in the first lines of script:
from __future__ import print_function
= assignment operator
== Operator to check value equivalence
is Operator to check identity of objects; looks at object level
in Operator to check identity of objects; looks at index level
!= not-equal-to operator
<> not-equal-to operator. Available only in python2.
# comment operator in python; called as octothorpe/pound/hash/mesh
>>> Input operator, shows readiness of interpreter. Called as chevron
^ bit-wise operator. Not power operator. Called as caret
; used to separate TWO or more statements in the same line.
‘‘‘ ’’’ or “““ ””” docstrings. Used for multiple-line comment in python scripts. Differs from using #. Appears in the output. Useful, especially, in modules.
#! Called shebang. Used as the first character in python script.
\ line-continuation operator. Used when a statement spans more than one line.
Eg: print “Udhay\
Prakash”
() used for tuples
[] used for lists
{} used for dictionaries
([]) used for sets
Switch-case condition is not defined in python. Instead, If-elif-else ladder can be used. Also, dictionary of functions can be used.
Eg:
>>> result={
... 'a':lambda x :x*5,
... 'b':lambda x:x+7,
... 'c':lambda x:x-2}
>>> result['b'](10)
17
Indentation is both boon and bane (for beginners) for python. Use spaces instead of Tabs in scripts.
Eg:
>>> a=2
>>> a
2
>>> a=2
Traceback ( File "<interactive input>", line 1
a=2
^
IndentationError: unexpected indent

Running python with –t option prints warning messages when tabs and spaces are mixed inconsistently within the same program block.
Running python with –tt option turns these warning messages in to TabError exception.
raw_input() takes any input as string type.
input() takes any input type dynamically.
&&,|| are defined operators in python
and boolean operator for AND operation
or boolean operator for OR operation
not Boolean operator for NOT operation
set operators
| union operator for sets
& intersection operator for sets
  • Set difference operator
Eg: c=t-s# set c contains items in set t, but not in set s
^ Symmetric difference operator for sets
Eg: d=t^s # set d contains items in set t or set s, but not common items in both.




bitwise Operators
& bit-wise AND operator
| bit-wise OR operator
^ bit-wise XOR operator
~ bit-wise invert operator. Eg: ~5 results in -6
Bit-wise invert of x is –(x+1)
>> left shift operator
Eg: 15>>1
7
Explanation: 15-1111 (in 8421 convention)
15>>1 means shifting one position left.
It becomes 0111 i.e., 7
<< right shift operator
** power of operator
/ division operator
// floor division operator (only in python3)
% modulo operator. Returns remainder of a division.

PEP8 suggests (not mandatory) for a white space around any operator.
It is suggested to define default parameters in the last, for functions.


By default, Python source files are treated as encoded in UTF-8.
To use different encoding for source files, it must be specified in the second line, after #! line, in the script.
Format: # -*- coding: encoding -*-

When you use Python interactively, it is frequently handy to have some standard commands executed every time the interpreter is started. You can do this by setting an environment variable named PYTHONSTARTUP to the name of a file containing your start-up commands. This is similar to the .profile feature of the Unix shells.

range(init_value,final_value,step_size)returns integers from init_value, till final_value, in steps of step_size. It doesn’t include final_value. The step_size MUST be either positive or negative integer; not a float value.

xrange() is same as range(); but, results in values only when essential. Available only in python2.

Python supports range() data-type. So, xrange() is not required.
{} are used to create both a dictionary type and set type.
Set contains only (unrepeated) elements; whereas dictionary contains keys and elements. Keys can’t be repeated, but elements in dictionary can be repeated.

Empty set must be created as var_name=set(), instead of var_name={}. The later creates an empty dict type variable.

When the Python interpreter is invoked with -O flag, code optimized .pyo files, are generated. This optimizer only removes assert statements. When -O is used, all bytecode
is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.

Similarly, passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations. Currently only __doc__ strings are removed from the bytecode, resulting in more compact .pyo files.

Only difference between
.pyc and .pyo code is the speed with which they are loaded.

The module compileall can create .pyc files (or .pyo files when -O is used) for all modules in a directory.

One space will be added between arguments, when print function/statement is used, in py3/py2 respectively.

Str.zfill() pads a numeric string on the left with zeros. It understands both plus and minus signs.
Eg:
>>> '23'.zfill(6)
'000023'
>>> '-3.14'.zfill(6)
'-03.14'
>>> '-3.14'.zfill(8)
'-0003.14'

Str.format()
>> print "This is {} and {}".format('GOOD','BAD')
This is GOOD and BAD
>> print "This is {1} and {0}".format('GOOD','BAD')
This is BAD and GOOD
>>print "This {food} is {adjective}".format(food='RICE',adjective="THE BEST ")
This RICE is THE BEST


>>> ord('a')
97
>>> chr(97)
'a'
>>> '\u011f'
'ÄŸ'

Hidden precision Limitation for python:
>>> 0.1+0.1
0.2
>>> 0.1+0.1+0.1
0.30000000000000004
>>> 0.1+0.1+0.1+0.1
0.4
It is recommended not to follow precision values.

Python can store any large number. Practically, it depends on the system memory of the machine.

Float is not exact.
>>> 4294967296.0**2
1.8446744073709552e+19
>>> 4294967296**2
18446744073709551616
1.8446744073709552×101918446744073709552000- 18446744073709551616=384
Float can be accurate upto 17 significant figures.

floating point numbers have limits both in terms of the largest and smallest numbers they can contain.
In total, floating point values have limited size and limited precision.

Textual comparison
>>> 'cat'<'dog'#Alphabetic ordering
True
>>> 'Cat'<'cat'#Uppercase before lowercase
True
>>> 'Dog'<'cat'#All uppercase before lowercase
True
Note: Ordering text is called “collation”, and is a complicated field. Python inequalities use Unicode character numbers for collation.

Order of precedence for OPERATIONS:
From highest to least:

x**y -x +x x%y x/y x*y x-y x+y x==y x!=y x>=y x>y x<=y x<y
not x x and y x or y

>>> -3**2 #** has higher precedence, compared to -
-9
>>> (-3)**2
9
All the operators except ** are left-associated, that means that the application of the
operators starts from left to right.

Unpacking
>>> a,b=10,7
>>> (a,b)=(a+b,a-b)#tuples
>>> a,b
(17, 3)
>>> a,b=a+b,a-b #lists
>>> a,b
(20, 14)

Four spaces’ indentation indicates a “block” of code in python. This can be observed in any for, while….blocks

The immutability of tuples means they’re faster than lists.

Lists
>>> l=[1,2,[3,4,[5,6,7]]]
>>> len(l)
3
No arithmetic operation can be performed between lists.
+ acts as a appending operator
>> a=[1,2]
>>> b=[2,3]
>>> a+b
[1, 2, 2, 3]
>>> a*3
[1, 2, 1, 2, 1, 2]

Note: All these facts are written after thorough verification. I request the readers to comment any modifications and suggestions. 

Comments

Popular posts from this blog

NSG 2.1 Tcl/OTcl Script Generator

Are you a beginner for ns2 network simulator? Are you afraid of Tcl/oTcl script generation? Then there is a tcl script generator, named NSG 2.1 NSG - Network Simulation Generator NSG 2.1 is a java .jar file.  So, this application can run on all platforms (windows/linux/mac os). It deserves the java installed in you pc, prior to working with NSG 2.1. Java must be installed to run NSG2.1. So, initially, java must be installed. How to install java in Windows/ubuntu/mint/debian linux/ OS X ? Step 1 : Go to Terminal and run  java -version   to check the java version installed in your machine. Step 2 :  For Windows, click here  to download the java installer. Then, it is a typical next-next windows executable installation. For ubuntu/mint/debian linux operating systems, run the following commands in that terminal: sudo apt-get install default-jre sudo apt-get install default-jdk sudo apt-get install openjdk-7-jre sudo apt-get install...

List of Websites to get free e-books

Here follows the list of websites to download e-books for free. 1. www.bookfi.org 2. www.bookzz.org  These two websites offer 4 to 5 free downloads per day. Best advantage is that we need not go for any sign-in process or clicking on an advertisement. 3. http://manybooks.net      In this website, apart from downloading in pdf format, one can download in many other e-book formats. 4. www.ebookee.org 5. www.bookboon.com 6. www.gutenberg.org 7. www.books123.me   8. www.brupt.com This website provides file in word (.doc), powerpoint (.ppt) and pdf file formats. 9. www.pdfoxy.com This website provides books in pdf format, but we should wait for 12-15 seconds and enter a Captcha code. But no need to sign-in. 10. www.docstoc.com This is another decent website of downloading ebooks in .pdf format, with no advertisement and no signing in. 11. www.freecomputerbooks.com This is one of the best websites for downloading technical and profession...

SUMO installation in linux (Debian/Ubuntu/Mint)

SUMO - S imulation of U rban Mo bility SUMO an open source, portal, microscopic, multi-modal road traffic simulation. It allows for intermodal simulation including pedestrians and comes with a large set of tools for scenario creation.  It allows to simulate as to how a given traffic demand which consists of single vehicles moves through a given road network. The simulator allows to address a large set of traffic management topics. It is purely microscopic: each vehicle is modeled explicitly, has an own route, and moves individually through the network. SUMO Installation Procedure: Installation in Linux and mac OS Step I: Install two pre-requisite packages to build SUMO with GUI. Go to terminal and run: $ sudo apt-get install libgdal1-dev proj libxerces-c2-dev $ sudo apt-get install libfox-1.6-dev libgl1-mesa-dev libglu1-mesa-dev Step II: If you are using Unbuntu 12.04 or older versions, as it doesn't ship with libgdal package, create a symbolic link: $ sudo ln -s /usr/l...