Python is an interpreted language, so that one need not to compile
every piece of code. The programmer can just write the command and then see the
output at the command prompt.
Many development environments are available for Python, for instance:
i) PyDev with Eclipse
ii) Emacs
iii) Vim
iv) TextMate
v) Gedit
vi) IDLE
vii) PIDA (Linux)(VIM based)
viii) NotePad++ (Windows)
ix) BlueFish (Linux)
To be able to write a program in Python, the programmer can use Anaconda. Note that for an electron microscopist, IDLE and
Anaconda are enough for routine programming. The basic steps of the installation of Python and its additions are described at Python Appendix.
Table 945a. Python keywords. These are words having special meanings and are understood by the
interpreter.
Keywords |
Meanings and applications |
if |
if <test condition>:
<block if the test condition is true>
An if can have any number of if's nested within. |
if-else |
if <test condition>:
<block if the test condition is true>
else:
<block if the test condition is not true>
If there are multiple else statements, then the second else is taken
along with the nearest if. code1, code2, code3, code4. |
If else ladder |
if <test condition>:
< The task to be performed if the condition 1 is true>
elif <test 2>:
<The task to be performed if the condition 2 is true>
elif <test 3>:
<The task to be performed if the condition 3 is true>
else:
<The task to be performed if none of the above condition
is true>
It is used when there are multiple conditions and the outcomes decide the action. Here, a switch is used in the case where different
conditions lead to different actions.. |
ternary |
The ternary operator performs the same task as the if-else construct.
Syntax:
<Output variable> = <The result when the condition is true>
if <condition> else <The result when the condition is not
true>
code |
and |
|
del |
|
from |
|
not |
|
while |
The while loop repeats a block, identified by indentation, until the test condition
remains true. The while loop is the most commonly used construct for repeating a
task over and over again. The
loop uses break and continue. code1, code2, code3. With for, you generally get a fixed number of loops, one for each item in a
range or one for each item in a list. With a while loop, the loop keeps going as long
as (while) some condition is true. |
for |
The for
construct is generally used for lists, tuples, strings, etc. E.g. repeating a Process with for, code. With for, you generally get a fixed number of loops, one for each item in a
range or one for each item in a list. With a while loop, the loop keeps going as long
as (while) some condition is true. |
as |
|
elif |
|
global |
|
else |
code1, code2. |
pass |
|
Yield |
|
break |
code1, code2 |
except |
|
import |
|
class |
|
raise |
|
continue |
code |
finally |
|
return |
code |
def |
|
try |
|
Functions are the units which perform a particular task, take some input, and
which may give some output. A function can
have any number of arguments. A function may or may not return a value. The parameters are basically the
input to a function.
Table 945b. Examples of functions and modules.
Command |
Comments |
Syntax of a function |
def <name of the function> (list of parameters):
<body>
code |
open() |
code |
lambda |
Lambda functions can be used in places where we expect variables. code. |
integrate.quad |
Numerical integration. code. |
scipy.integrate |
Numerical integration |
Table 945c. Some functions from the python math module.
Command |
Comments |
import math |
It imports math. Example code |
math.ceil() |
The ceiling of a given number is the nearest integer greater than or
equal to that number. For example, the ceiling of 4.568 is 5. Code |
math.floor() |
The floor of a given number is the nearest integer smaller than or
equal to that number. For example the floor of 4.68 is 4 and that of 4 is also 4. |
math.sqrt() |
Calculate the square root of a
number by importing math and using math.sqrt() |
math.acos() |
Returns the arc cosine of x in radians. |
math.atan() |
Returns the arc tangent of x, in radians. |
math.e |
Returns the mathematical constant e (2.718281 . . .). |
math.pi |
Returns the mathematical constant pi (3.141592 . . .). |
math.exp() |
Returns e raised to the power x, where e is the base of natural logarithms. |
math.pow(x, y) |
Returns x raised to the power y. code1, code2. |
math.log(x,y) |
Returns the natural logarithm of x to base y. |
math.log2(x) |
Returns the base-2 logarithm of x. |
math.expm1() |
|
math.radians(x) |
Converts angle x from degrees to radians. |
math.tan(x) |
Returns the tangent of x radians. |
math.acosh() |
|
math.atan2() |
Returns atan(y / x), in radians. |
math.cos() |
|
math.erf() |
|
math.fabs() |
The absolute value of a number |
math.sin(x) |
Returns the arc sine of x, in radians. |
math.asin() |
|
math.atanh() |
|
math.cosh() |
|
math.erfc() |
|
math.factorial() |
Factorial: The factorial of a number x is defined as the continued product of
the numbers from 1 to that value. code. |
math.tau() |
Returns the mathematical constant tau (6.283185 . . .). |
math.asinh() |
|
math.ceil() |
|
math.degrees() |
Converts angle x from radians to degrees. |
math.isnan(x) |
Returns True if x is not a number, otherwise returns False. |
math.copysign(x, y) |
Copy sign: The sign of the second argument is returned along with the result
on the execution of this function. x: Integer value to be converted,
y: Integer whose sign is required. Example code |
Table 945d. Special Python functions/comments.
|
|
[... : ...] |
Slicing, in strings, refers to removing some part of a string. Example code. |
name() |
E.g. name[0] and
name[1] prints the first and second letter of the string, respectively.
However, negative indexing, -n, in a string refers to the character present at the nth position beginning from the end. Example code |
len() |
It returns
the length of the string. Plus: The last character of a given string can also be printed. Example code |
→ |
It can print the first and the second last characters. Example code. |
input() |
The function is used to gather data from the user. code1, code2, code3. |
space used in scripts |
Example code |
range() |
Using range() in a for loop is optional. code1: pattern, code2: numbers, code3: numbers, code4: number pattern. |
.get() |
A switch statement. code. |
fractions/decimal
|
Example code |
Table 945e. Python variables, operators and sequences.
|
|
Variables |
In order to store and use the values later, we need variables. |
Numbers |
Python has three types of numbers: integer, floating point and complex. |
Integer |
It does not have any fractional part. int: Example code. |
Floating Point |
It can store number with a fractional part |
Complex |
It can store real and imaginary parts |
Decimal |
Those having fixed precision |
Rational |
Those having a numerator and a denominator |
Sets |
Abstraction of a mathematical set |
|
|
Conversions |
Cast, or convert a variable from one type to another. |
int() |
Converts a float number or a string to an integer, cast the number |
float() |
Returns a floating point number constructed from a number or string |
str() |
Returns a string which is fairly human readable. code. |
chr() |
Convert an integer to a string of one character whose ASCII code is same as the integer |
complex() |
Print a complex number with the value real + imag*j or convert
a string or number to a complex number |
ord() |
Returns an integer representing Unicode code point for the given
Unicode character. code |
hex() |
Convert an integer number (of any size) to a lowercase hexadecimal string prefixed with
“0x” |
oct() |
Convert an integer number (of any size) to an octal string prefixed with “0o” |
|
|
Operators |
These are special symbols which help the programmer to carry out
operations |
Arithmetic operators |
|
+ |
Addition. Example code for string, Example code for tuple . |
- |
Subtraction |
* |
Multiplication. For a string, it concatenates a given string the number of times, given
as the first argument. Example code for string. |
** |
Exponentiation |
/ |
Division |
// |
|
% |
Modulo: The modulo operator finds the remained if the first number is greater
than the other, otherwise it returns the first number as the output. E.g. 4%6 = 4 |
% |
For function. code. |
|
|
Assignment operators |
|
= |
|
+ = |
|
– = |
|
*= |
|
/= |
|
%= |
|
**= |
|
//= |
|
|
|
or/| |
The output is 'true', if any
of the conditions are 'true'. Example code. |
and/& |
The output is 'true' or 'false', when both the
conditions are 'true' or 'false'. Example code. |
not |
|
Relational operators |
Also called comparison operators. The output of these comparison operators is always a Boolean value, either True or False.
The operands can be Numbers or Strings or Boolean values. Strings are compared letter
by letter using their ASCII values. |
< |
Lesser than:
If the value of left operand is less than the value of right
operand, then condition becomes True. |
<= |
Lesser than or
equal to: If the value of left operand is less than or equal to the
value of right operand, then condition becomes True. |
> |
Greater than: If the value of left operand is greater than the value of
right operand, then condition becomes True. |
>= |
Greater than or
equal to: If the value of left operand is greater than or equal to the
value of right operand, then condition becomes True. |
!= |
Not Equal to:
If values of two operands are not equal, then the
condition becomes True. |
< > |
|
== |
Equal to:
If the values of two operands are equal, then the
condition becomes True. |
|
|
Objects |
Everything in Python is an object. Each
object has identity, a type, and a value. |
Identity |
The identity, in Python, refers to the address and does not change. |
string |
A string is a predefined object which contains characters. Loop through a string from left to right: code1, code2. |
Old Style String Formats |
|
%d |
Decimal integers (not floating point). code. |
%i |
Same as %d |
%o |
Octal number |
%u |
Unsigned decimal |
%x |
Hexadecimal lowercase |
%X |
Hexadecimal uppercase |
%e |
Exponential notation, lowercase “e” |
%E |
Exponential notation, uppercase “E” |
%f |
Floating point real number |
%F |
Same as %f |
%g |
Either %f or %e, whichever is shorter |
%G |
Same as %g but uppercase |
%c |
Character format |
%r |
Repr format (debugging format) |
%s |
String format |
%% |
A percent sign |
|
|
Sequences |
These are ordered collections of elements. There are three types of
sequences in Python: string, tuples and lists |
Escape sequences |
Are a combination of a backslash (\) followed by either a letter or a
combination of letters and digits. |
\t |
Inserts a Tab in the string. Example code |
\ |
Break a Line into Multiple lines while ensuring the continuation of the line |
\\ |
Inserts a Backslash character in the string |
\' |
Inserts a Single Quote character in the string |
\" |
Inserts a Double Quote character in the string |
\n |
Inserts a Tab in the string |
\r |
Inserts a Carriage Return in the string |
\b |
Inserts a Backspace in the string |
\u |
Inserts a Unicode character in the string |
\0oo |
Inserts a character in the string based on its Octal value |
\xhh |
Inserts a character in the string based on its Hex value |
|
|
String
|
A string is a predefined object which contains characters. Example code |
Tuples |
A tuple contains elements which can be treated individually or as a group. A tuple may also contain heterogeneous elements (e.g. a string and an integer): Example code. Tuples are useful in operations like swapping etc.: Example code1, Example code2 |
Lists |
A list is a collection of objects. Unlike strings, lists are mutable. A list can also contain list(s). code1, code2: roop, code3: roop, code4: roop. |
.index() |
It is an inbuilt function in Python, which searches for a given element from the start of the list and returns the lowest index where the element appears. The index of the first location is 0. Syntax: list_name.index(element, start, end). code1, code2 |
|
|
Table 945f. Attributes of user-defined functions.
name |
type |
description |
__annotations__ |
dict |
parameter and return annotations |
__call__ |
method-wrapper |
implementation of the () operator; a.k.a. the callable object protocol |
__closure__ |
tuple |
the function closure, i.e. bindings for free variables (often is None) |
__code__ |
code |
function metadata and function body compiled into bytecode |
__defaults__ |
tuple |
default values for the formal parameters |
__get__ |
method-wrapper |
implementation of the read-only descriptor protocol (see XREF) |
__globals__ |
dict |
global variables of the module where the function is defined |
__kwdefaults__ |
dict |
default values for the keyword-only formal parameters |
__name__ |
str |
the function name. Example code |
__qualname__ |
str |
the qualified function name. Example code |
Table 945g. Methods of the mapping types dict, collections.defaultdict and collections.OrderedDict (common object methods omitted for brevity). Optional arguments are enclosed in «...».. |
Methods |
Dict |
Default
dict |
Ordered dict |
|
d.clear() |
✔ |
✔ |
✔ |
remove all items |
d.__contains__(k) |
✔ |
✔ |
✔ |
k in d |
d.copy() |
✔ |
✔ |
✔ |
shallow copy |
d.__copy__() |
|
✔ |
|
support for copy.copy |
d.default_factory |
|
✔ |
|
callableinvokedby __missing__ toset missing values |
d.__delitem__(k) |
✔ |
✔ |
✔ |
del d[k] — remove item with key k |
d.fromkeys(it, «initial») |
✔ |
✔ |
✔ |
new mapping from keys in iterable, with
optional initial value (defaults to None) |
d.get(k, «default») |
✔ |
✔ |
✔ |
get item with key k, return default or none if missing |
d.__getitem__(k) |
✔ |
✔ |
✔ |
d[k] — get item with key k |
d.items() |
✔ |
✔ |
✔ |
get view over items — (key, val ue) pairs |
d.__iter__() |
✔ |
✔ |
✔ |
get iterator over keys |
d.keys() |
✔ |
✔ |
✔ |
get view over keys |
d.__len__() |
✔ |
✔ |
✔ |
len(d) — number of items |
d.__missing__(k) |
|
✔ |
|
called when __getitem__ cannot find the key |
d.move_to_end(k, «last») |
|
|
✔ |
movekfirstorlastposition(lastisTrue by default) |
d.pop(k, «default») |
✔ |
✔ |
✔ |
remove and return value at k, or de
fault or None if missing |
d.popitem() |
✔ |
✔ |
✔ |
remove and return an arbitrary (key, value) itemb |
d.__reversed__() |
|
|
✔ |
get iterator for keys from last to first inserted |
d.setdefault(k, «de
fault») |
✔ |
✔ |
✔ |
if k in d, return d[k]; else set d[k]
= default and return it |
d.__setitem__(k, v) |
✔ |
✔ |
✔ |
d[k] = v — put v at k |
d.update(m, «**kargs») |
✔ |
✔ |
✔ |
update d with items from mapping or
iterable of (key, value) pairs |
d.values() |
✔ |
✔ |
✔ |
get view over values |
Table 945h. Examples of Python applications.
Applications |
Examples |
Reverse the digits of a given number |
code |
Palindrome repeat |
code |
Find the greatest of three numbers |
code1, code2, code3. |
Find/search birthyear by name |
code |
Loop through numbers in a range |
code |
Loop through a list |
code1, code2, code3 |
Loop through a string from left to right |
code1, code2 |
Bail out/terminate of a loop |
code |
Reference list items by position |
code1, code2 |
Search position of numbers |
code |
Swap two numbers |
code |
Computing equations and formulas with Python |
Examples. Numerical integration at code. |
Two types of files can be handled in python, normal text (.txt) files and binary files.
Table 945i. Files which can be handled in python.
Codes |
Details |
‘r’
|
Read Only: Open text file for reading. The handle is positioned at the beginning of the file. code |
‘r+’ |
Read and Write: Open the file for reading and writing. The handle is positioned at the beginning of the file. code |
‘w’ |
Write Only: Open the file for writing. For existing file, the data is truncated and over-written. |
‘w+’ |
Write and Read: Open the file for reading and writing. For existing file, data is truncated and over-written. |
‘a’ |
Append Only () : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. |
‘a+’ |
Append and Read: Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data. |
read([n]) |
Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file. code |
readline([n]) |
Reads a line of the file and returns in form of a string. For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line. |
readlines() |
Reads all the lines and return them as each line a string element in a list. |
read line-by-line |
With double-spaced output, code; by getting rid of that effect of double-spaced output code. |
close() |
It closes the file and frees the memory space acquired by that file. |
|