Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Python CheatSheet - Sahil

Uploaded by

Sahil Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Python CheatSheet - Sahil

Uploaded by

Sahil Saini
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PYTHON QUICK-REVISION (Basic)

• Python has a python shell window, or prompt, to run or try out individual commands – like a calculator. But
unlike a calculator, it can do more than arithmetic, e.g. you can write print(x)
o Working with Jupytor is like the prompt. You tell commands (which can be complex) and run them
immediately, then you go to next command and so on.
o This also means there is no compilation in Python. The code directly runs. Like mathematica, Python
directly interprets the code. What does that mean? Is the object code not made?
o Python is a scripting language. A script consists of a list of commands, which the Python interpreter
changes into machine code one line at a time. Those lines are then executed by the computer.
o In a compiled language, all instructions are analyzed and converted to machine code by the compiler
before the program is run. Once compilation is finished, program can run very fast. In an interpreted
language, each command is analyzed and converted “on the fly" - makes it significantly slower, but
easier to tweak and debug because you don't have to re-compile after every change. Another
benefit - one can experiment with simple Python commands by using the Python interpreter directly
from the command line.
• But normally we want to write an entire program consisting of a set of instructions (“statements”) and run
them together -> the usual “program”. That’ what we discuss below:

Structure of program/ general info:

• No need to specify the beginning or end of program – was unnecessary anyway. That is, no `void main()’ or
`program abc’ or `END’ required.
• This also means, when you define external function. After the definition of the function ends, you don’t have
to begin the main program, its already on (see some examples).
• Case sensitive
• Assignment statement work as it does in C or Fortran
• Commenting starts with #
• adding spaces in a statement, e.g. “x = 1” has no effect. Can add blank lines to separate sections of code
• Cannot add spaces at the beginning of a line
• Division : “x/y” gives float answer – full division, “x//y” gives quotient, “x%y” gives remainder. The modulo
operation also works for floats, e.g. 1.5 % 0.4 gives 0.3
• Precedence level: power > multiplication or division > addition or subtraction. Within multiplication or
division – whichever comes first when going from left to right.
• Containers – lists, arrays, tuples, dicts and sets - for storing collections
• Split long program lines using “\” at the end of a line - it tells the computer that the following line is a
continuation of the current one.

Variables: are the quantities of interest in a given program, e.g. vectors, scalars, real numbers, matrices

• naming – can be as long as you like, can contain letters, numbers and underscore “_” but cannot start with a
number, or contain any other symbols or spaces.
• Types:
o Integers
o Float – can also store integer values as a special case, but takes more space
o Complex – can also store reals as a special case – note that complex unit is denoted “j” in python
instead of “I”, e.g. 3+9j
o String – can be enclosed in either single or double quotes, no difference
o No separate long or double type, the integer/float type can handle any large number
• Its better to use the variable of the appropriate type. Even though complex can store float type values, but it
takes double the space of float, as the imaginary part has to be specified to be zero.
o Moreover, calculations with complex take longer as the imaginary part has to be calculated even if it
is zero. Moreover, if you need to use only integers, its better to use integer variable as they will give
better accuracy.
o In many applications, some variables can’t have decimal points, e.g, the quantum numbers in QM
are integers
• Declaration: unlike C and Fortran, declaration and initiation combined. No separate declaration needed:
o The type is determined by the assignment. E.g. when you first write “x=1”, automatically x becomes
integer variable. Variables in Python get created when you first use them.
o This also means type of a variable can change during the program when they are given a new value,
e.g. we may write the following lines one after the other:
X=1
X=1.5
X=1.2e-12 + 2.0e10 j
X=float(1) # take 1 and make it a float
X=complex(2.5)
X=”This is a string” # x now becomes a string variable
This is unlike static-typed languages such as C, Fortran and Java
o However, just because can change the type of variable like this, doesn’t mean you should – poor
programming practice to use the same variable for two different types – leads to confusion making
you susceptible to make mistakes while writing the program – program becomes difficult to follow
o The ability to assign two variables values simultaneously (unlike other languages): e.g.
x,y = 2.5, x+3.0
In this, the whole rhs is calculated and then assignment is made to both variables. This can be useful,
e.g. to interchange values
x,y = y,x
• Result of a calculation depends on the types of variables involved, e.g.
o x=a+b # if a and b are of different type, the end result has more general of the two types, it applies
to other arithmetic operations as well.

Input/Output statements:

• Examples: (in earlier versions of Python the print statement didn’t have parentheses)
print(x)
print(x,y)
print(x+y)
print(“the value of x is ”,x,“ and the value of y is ”,y)
• Occasionally you may want to print variables with other than spaces in between, e.g.
x=1.5
z=2+3j
print(x,y,sep=``….”)
This would print
1.5…2+3j
• The basic format of input statement
x=input()
X=input(“Enter the value of x:”)
However, the entered value is by default interpreted as a string value. Thus we may want to write
X=float(input(“Enter the value of x:”))
o If we know that the value entered will be float.

Lists: ordered, mutable, allow repeated elements, can contain different data types in the same list. Square brackets

• Example
x,y = 3, 2+8j
mylist = [“apple”, 5, x, True, “apple”, y/sqrt(x)]
# this list has a repeated string, an integer, a Boolean etc.
print(mylist) # this will print the entire list
• Individual elements are denoted mylist[0], mylist[1],… etc., which behave like single variables
o We can treat them like single variable, e.g. we can change them, mylist[3] = False
• Operations on entire lists using built-in functions:
r = [1.0, 2.0, -12.0]
Total = sum(r)
Mean = sum(r) / len(r) # len finds length of list
x,y = max(r), min(r)
r = r.append(1.6) # add elements to an existing list
r.pop() # removes the last element
r.pop(3) # removes the element r[3]
q = [] # creates empty list
t = list() # creates empty list
logr = list(map(log,r)) # a new list logr is created from r

Note: map operation is like the map in mathematica – applies an ordinary function to each element of the
list. It creates a specialized object in computer memory called iterator, thus we use list function to convert
and store it into a new list. The difference between an iterator and a list is that the values in an iterator are
not stored in the computer’s memory. Instead, the computer calculates them on the fly when they are
needed, which saves memory. Thus, in this case, the computer only calculates the logs of the elements of r
when you convert the iterator to a list. In older versions of Python, map function produced a list, not an
iterator, so if you are using an earlier version of the language you do not need to convert to a list using the
list function.

Arrays:

• Compared to lists: the number of elements in arrays is fixed, and they all have to be of same type. And the
type can’t be changed once the array has been created. Unlike lists, arrays can be higher dimensional. Since
arrays are simpler, calculations with them are faster, specially if you have large number of elements.
• It is easiest to create arrays using functions from numpy package:
from numpy import zeros
a = zeros(4,float)
print(a) # results in 0. 0. 0. 0.
Similarly we have zeros(3,int) or zeros (100,complex). We can also create and initialize a 2D array with zeros
like this. E.g.
a = zeros([3,4], int) # gives a 3x4 matrix with all entries zero
o Note that the first element inside the function zeros in this case is itself a list, whose elements
specify the size of the matrix
There’s another function ones in numpy which works similar to zeros
• On the other hand, if we are going to change the values immediately after we create the array, no point in
having the computer set all of them to zero (or one) first. For this:
from numpy import empty
a=empty(4,float) # these will be filled with garbage value instead
• Convert a list, using function array from numpy:
r = [ 1.0, 1.5, -2.2 ]
a = array(r,float)
b= array( [[1,2,3],[4,5,6]], int) # creates 2D matrix using a list
of two lists
you can also convert an array to list as follows: r=list(a)
• Reading an array from file: a = loadtxt(“values.txt”,float) # loadtxt in numpy
The file has to be in the same folder for this to work, or you have to specify the full path to file. If the file
contains a 2D grid, the array created will be 2D.
• Arithmetic with entire arrays: e.g.
a = array([1,2,3,4],float)
b=2*a # multiplying whole array by a constant
print(a+b) # sum of two arrays, a and b have to be of same size
print(a+1, a*b) # add 1 to all elements and the product of
corresponding elements, division works similarly
All these element-wise operations work similarly on multi-dimensional arrays as well.
print(dot(a,b)) # gives the usual dot product for 1D vectors, and the matrix product for 2D
matrices a and b. e.g.
a = array([[1,3],[2,4]],int)
b = array([[4,-2],[-3,1]],int)
c = array([[1,2],[2,1]],int)
d = array([0,7,1],int)
print(dot(a,b)+2*c)
print(dot(a,d),dot(d,a)) # python automatically considers d as a column vector in first
case and as a row vector in the second
o function map can be used to apply any function to array elements similar to its the application to
lists
o Functions sum, map, min, max, len can be applied to 1D arrays similarly to lists. When
applies to 2D or higher, they produce erratic results or error messages. However numpy has function
which do these things for 2D and higher arrays e.g. min, max, size, shape functions in
numpy. a.size returns the total number of entries in an array, a.shape returns a list specifying
the dimensions. E.g. if we write n=a.shape where a is 2D array, then n[0] is the number of rows and
n[1] is no of columns.
• Example: to find the mean-square value and geometric mean:
from numpy import loadtxt
from math import log, exp
values = loadtxt("values.txt",float)
meansq = sum(values*values)/len(values)
logs = array(map(log,values),float)
geometric = exp(sum(logs)/len(logs))
print(meansq)
print(geometric)
• A word of caution. Look at the following program:
from numpy import array
a = array([1,1],int)
b = a
a[0] = 2
print(a,b)
it prints [2,1] and [2,1]. In python, direct assignment of arrays as “b=a” just creates b as another
name for a, and not a new array called b (similar to how it works in C). If you want to create a copy,
write “b=1*a” or “b=copy(a)” using copy from numpy.
• Slicing: useful trick, works with both arrays and lists. Suppose we have a list r. Then r[m:n] is another list
composed of a subset of the elements of r, starting with element m and going up to but not including
element n. Variants r[m:] (from m onwards), r[:n] (upto n excluding n), r[:] (all elements, this one is
more useful for 2D arrays), a[2,3:6], a[:,3] (gives 4th column).

If statement:

• No brackets for enclosing the condition. A colon is used. No brackets to enclose the statements contained in
if, this are conveyed through indentation. How many spaces to specify indentation – as many as you like, one
upwards.
• Example
if x>10 or x<1:
print("Your number is out of range.")
print(“So we will take the default value”)
x=9
elif x>9:
print("Your number is OK, but you’re cutting it close.")
print(x)
else:
print("Your number is fine. Move along.")
While Loop:
x = int(input("Enter a whole number no greater than ten: "))
while x>10:
print("This is greater than ten. Please try again.")
x = int(input("Enter a whole number no greater than ten: "))
print("Your number is",x)

The while statement can also be followed by an else statement, which is executed once (and once only) if and
when the condition in the while statement fails. (This type of else statement is primarily used in combination with
the break statement). There’s no equivalent of elif statement for while

Break statement:

• To break out of a loop. E.g.


while x>10:
print("This is greater than ten. Please try again.")
x = int(input("Enter a whole number no greater than ten: "))
if x==111:
break
• If the while loop is followed by an else, the else part is not executed after break. Break statement allows you
to create a program that does different things if the while loop finishes normally (and executes the else
statement) or via a break (in which case the else statement is skipped).

Continue statement:

Saying continue anywhere in a loop will make the program skip the rest of the indented code in the while loop
and go to the next iteration.

For Loop: a loop that runs through the elements of a list/array in turn

• Typical example
r = [ 1, 3, 5 ]
for n in r:
print(n)
print(2*n)
print("Finished")
• Break and continue can be used with similar effect. break ends the loop. continue abandons the current
iteration to move on to next iteration.
• Range – a built-in function, creates a list of given length.
o Range(5) creates list [0,1,2,3,4], range(2,8) gives [ 2, 3, 4, 5, 6, 7 ] and
range(20,2,-3) gives [ 20, 17, 14, 11, 8, 5 ].
o Technically range function produces an iterator. To get a list one has to write list(range(5)).
But you are allowed to use an iterator directly in a for loop. E.g.
r = range(5)
for n in r:
print("Hello again")
for n in range(2,11):
print(n**2)
for n in range(p//q):
print(n)
• A similar function is arange from numpy package – gives arrays instead of list/iterators and also works
with real arguments as well, e.g. arange(1.0,8.0,2.0) gives an array [1.0,3.0,5.0,7.0]
o Note: arange generates an actual array, calculating all the values and storing them in the
computer’s memory. This can cause problems if you generate a very large array because the
computer can run out of memory, crashing your program, an issue that does not arise with the
iterators generated by the range function. For instance, arange(10000000000) will produce
an error message on most computers, while the equivalent expression with range will not.
• Another similar function is linspace, also from the numpy package, which generates an array with a
given number of floating-point values between given limits. E.g. linspace(2.0,2.8,5) divides the
interval from 2.0 to 2.8 into 5 values, creating an array with floating-point elements
[2.0,2.2,2.4,2.6,2.8]
o Unlike both range and arange, linspace includes the last point in the range
o Also linspace always generates floating-point values, even when the arguments are integers.

Packages: – collections of related useful commands/functions.

• from math import log, log10


• from math import * (not advised to import the whole package, the package may contain,
unbeknownst to you, some functions whose names clash with your variable names or other user-defined
functions)
• If you import the whole package as import math, then the functions have to be referred to as
x=math.log(2.5), compared to the other method where they can be directly referred to.
• A particular problem is when an imported package contains a function with the same name as a previously
existing function. In such a case the newly imported one will be selected in favor of the previous one, which
may not always be what you want. For instance, the packages math and cmath contain many functions with
the same names, such as sqrt. But the sqrt function in cmath works with complex numbers and the one in
math does not. If one did “from cmath import *” followed by “from math import *”, one would end up with
the version of sqrt that works onlywith real numbers. And if one then attempted to calculate the square root
of a complex number, one would get an error message
Common packages –
math – log, log10, sin, asin, sinh, exp, sqrt, pi, e, etc.
cmath – contains most of the functions of math which also work with complex numbers

Some large packages are split into “modules” for convenience (for smaller packages like math, the words module
and package are used interchangeably). The modules are referred to as package.module
e.g. numpy contains large number of useful facilities, including for linear algebra and Fourier transform, e.g.
from numpy.linalg import inv
See details of built-in functions, and some standard packages.

User-defined Functions:

• Example: (notice the indentation– important as there are no brackets to mark beginning/end of things like a
loop or a function)
def factorial(n):
f = 1.0
for k in range(1,n+1):
f *= k
return f
• Variables created inside a function exist only inside that function (called local variables) – they can’t be used
outside. The reverse works - you can use a variable inside a function that is defined outside it – better to
avoid name clash with any variables inside the function.
• Arguments (as well as the value returned) can be of any type- integers, real and complex numbers, lists and
arrays, e.g. the following function returns a list:
def cartesian(r,theta):
x = r*cos(theta)
y = r*sin(theta)
position = [x,y]
return position
• In fact, we could combine the two final lines here into one and say simply return [x,y]. Or we could
return x and y in the form of a two-element array by saying return array([x,y],float). One can
also return multiple variables as return x,y. To call such a function we must use the multiple assignment
feature x,y = cartesian(1.5,3.14)
• User-defined functions can also return no value at all—it is permitted for functions to end without a return
statement, e.g.
def print_vector(r):
print("(",r[0],r[1],r[2],")")
• Its recommended to put all your functions at the beginning – so they appear before their first use, makes
them easier to find if you want to look them up or change them.
• You can also apply a user-defined function to all the elements of a list or array with the map function
• The functions you define do not have to be in the same file as your main program. You could, for example,
place a function definition for a function called myfunction in a separate file called
mydefinitions.py. You can put the definitions for many different functions in the same file if you want.
Then, when you want to use a function in a program, you say from mydefinitions import
myfunction. This way, these functions can be used in many different programs.

Classes:

A Class is like an object constructor, or a "blueprint" for creating objects. E.g. Create a class named MyClass, with a
property named x:

class MyClass:
x = 5
p1 = MyClass() # create an object p1 of MyClass
print(p1.x)
Use the built-in __init__() function to assign values to object properties, or other operations that are necessary to do
when the object is being created. The __init__() function is called automatically every time the class is being used to
create a new object:

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
# The self parameter is a reference to the current instance of the class,

# and is used to access variables that belong to the class.

p1 = Person("John", 36)

p1.myfunc()
print(p1.age)
You can delete properties on objects by using the del keyword, e.g. del p1.age

You can also delete objects: del p1

Data-file handling
Plotting/Graphics – see Newman chapter

Important packages to know – a page or half page for each

Also consult the book by Ayers, Byte of python etc. to add useful material.

Some basic packages:

Numpy package

Scikitlearn

Pandas

You might also like