The document provides information about getting started with iPython. It discusses how to install iPython, start iPython, use tab completion and help features. It also demonstrates basic math operations in iPython like addition, subtraction, multiplication, division and rounding numbers. The document then covers plotting graphs using iPython, embellishing plots, multiple plots and loading/plotting data from files. It also introduces key concepts in Python like lists, strings, files, arrays, conditionals, loops, tuples, dictionaries and sets. Finally, the document discusses functions and lambda functions in Python.
2. Installing iPython
Download Python : -https://www.python.org/downloads/
Download iPython :- pip install ipython
You can manually download IPython from GitHub or
PyPI.
3. Getting Started with iPython
How to Start iPython in Terminal : - ipython
Exit for iPython :- Clt + D
4. Getting Started with iPython
Tab Completion : - Pressing “tab” just after a starting word can help to auto complete the
function
Help Feature :- “Help” feature help us to know what function will do and how to use it - just put
“?” after function name.
5. Getting Started with iPython
Addition :-
iPython promptly gives back the output as 3. Notice that the output is displayed with an Out[1]
indication.
If not to print the Output as Out[comandnumber]
8. Getting Started with iPython
ABS :-
Clt + C :- if we commit a typing error with a longer and more complex expression and end up
with the continuation prompt, we can type Ctrl-C to interrupt the command and to get back to
the ipython input prompt.
9. Using Plot command Interactively
To Start with Plot - ipython-pylab
Pylab is a python library which provides plotting functionality. It provides many other important
mathematical and scientific functions.
How to Plot :-
1. Create a data set using linspace
2. Plot using command plot
13. Using Plot command Interactively
Create a dataset for whose graph to be plotted.
→ p=linspace(0,1,100)
Dataset created
→ plot(p,cos(p))
To erase the graph so that it should not be overlapped :-
→ clf()
To save the graph :-
→ savefig(‘/'/Users/juspay/Downloads/graph.png')
can be saved as png, pdf, xvg, pvg
14. Embellishing a Plot
Design the Graph -
→ plot(x,sin(x),’r’) - here r is for red color
→ plot(y,sin(y),’b’,linewidth=2)-linewidth to increase the width of
the line
→ plot(s, cos(s) ,’g’, ' . ') - to get plot in only point instead of line
→ title(“Parabolic Function -for different Commands”) - to give
title to the graph
15. Embellishing a Plot
Design the Graph -
→ xlabel(“x”) - to label x-axis
→ ylabel(“f(x)”) - to label x-axis
→ x label(“$”x”$) - to label x-axis in latex format
→ ylabel(“$”f(x)”$) - to label y-axis in latex format
16. Embellishing a Plot
Design the Graph -
→ annotate("Local Maxima", xy=(-4,0))
→ In [39]: xlim() Out[39]: (-5.5, 5.5)
→ In [40]: ylim() Out[40]: (-1.0237, 0.9388)
→ In [41]: xlim(-6,6) Out[41]: (-6, 6)
→ In [42]: ylim(-2,1) Out[42]: (-2, 1)
17. Multiple Plots
To differentiate the different plot :-
→ legend([ ‘sin(x)’ , ’sin(y)’ ])
→ legend([‘Parabola’ , ‘ Straight Line’ ])
→ figure(1) - use to name different graph
18. Multiple Plots
To differentiate the different plot :-
→subplot(numberofrowstobecreated,numberofcolumntobecreate,whatplotmustbecreatenow
)
E.g. subplot(2,1,1)
E,g, subplot(2,1,2)
19. Additional features of iPython
To see the history of commands used to plot the graph--
→ %hist
→ %hist 5 (for finding last 5 command
→ %hist 5 10 (to show command from 5 to 10
→ %save /home/download/graph.py 1 3 5 8 (to save selected
command only)
→ %run -i /home.download/graph.py (to run the sace
commands)
20. Loading data from Files
→ cat /home/download/graph.txt
→ prime=loadtxt(‘/home/download/graph.txt’)
→ print primes
22. Plotting the Data
→ L = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
→ T = [0.69,0.90, 1.19, 1.30, 1.47, 1.58, 1.77, 1.83, 1.94]
→ Tsquare = square(T)
→ errorbar(L, Tsquare, xerr=L ,yerr=Tsquare, fmt='bo')
23. Other type of Plots
Scatter plot : - The data is displayed as a collection of points,
where each point determines its position on the horizontal axis
and the vertical axis respectively. This kind of plot is also called
a scatter chart, a scatter diagram or a scatter graph.
Syntax :- scatter(year,profit)
first one the values in x-coordinate, year, and the other the
values in y-coordinate, the profit percentage.
24. Other type of Plots
Pie Chart : - A pie chart or a circle graph is a circular chart
divided into sectors, illustrating proportion.
Syntax : - pie(profit,label=year)
first one the values and the next one the set of labels to be used
in the pie chart.
25. Other type of Plots
Bar Chart : - A bar chart or bar graph is a chart with rectangular
bars with lengths proportional to the values that they represent.
Syntax 1 : - bar(year,profit)
one the values in x-coordinate and the other values in y-
coordinate which is used to determine the height of the bars.
Syntax 2 :- bar(year,profit,fill=False,hatch='/')
26. Other type of Plots
Log Log : - A log-log graph or a log-log plot is a two-dimensional
graph of numerical data that uses logarithmic scales on both the
horizontal and vertical axes. Because of the nonlinear scaling of
the axes, a function of the form y = axb will appear as a straight
line on a log-log graph
Syntax : - x= linspace(1,2,100)
y= 5*x**x
loglog(x,y)
27. Getting started with Lists
List is a compound data type, it can contain data of mutually different data types. List is also a
sequence data type where all the elements are arranged in a specific order.
Syntax :-
To declare the list⇒ The simplest way of creating a list is typing out a sequence of comma-
separated values (or items) between two square brackets.
To travel the list ⇒ We access an element of a list using its corresponding index. Index of the first
element of a list is 0.
⇒ Python negative indices are used to access elements from the end. -1 gives the last element
29. Getting started with Lists
Syntax :- len function to check the number of elements in the list.
del(nonempty[1]) → The function del deletes the element at index 1
30. Getting started with for
In Python whitespace is significant, and the blocks are visually
separated. The best practice is to indent the code using four
spaces.
31. Getting started with for
range() function :- range() is an inbuilt function in Python which
can be used to generate a list of integers from a starting number
to an ending number. Note that the ending number that you
specify will not be included in the list.
32. Getting started with String
What are strings?
In Python anything within either single quotes or double quotes or triple single quotes or triple double
quotes are strings.
34. Getting started with Files
Open the file :--
File object :--
Read method in pend:--
Print what pend read:--
35. Getting started with Files
⇒ pend_list :-- use the function splitlines to solve this problem.
⇒ f.close() :-- close the file opened into f.
⇒ Print_line :-- to read the file line-by-line, we iterate over the file object line-by-line, using the for
command.
⇒ line_list[] :-- instead of just printing the lines, let us append them to a list, line_list.
36. Parsing Data
⇒ split is called without any
arguments, it splits on
whitespace. In simple words,
all the spaces are treated as
one big space.
⇒ The function split can also
split on a string of our choice.
This is achieved by passing
that as an argument.
⇒ The function split can also
split on a string of our choice.
This is achieved by passing
that as an argument.
record.split(';')
37. Statistics
Sum of list:--
average of list:--
Need to include numpy header
Mean of list:--
Median of list:--
Std of list:--
import numpy
38. Getting started with Array
Arrays are homogeneous data structures. Unlike lists, arrays
cannot have heterogeneous data elements. They can have only
one type of data as their entries, be them all integers, strings, or
maybe floats, but not a mix.
Arrays of a given length are comparatively much faster in
mathematical operations than lists of the same length, because
of the fact that they are homogeneous data structures.
39. Getting started with Array
We can treat lists as arrays. However, we cannot constraint the type of elements stored in a list.
For example:
a= [1,3.4,”Hekki”]
If you create arrays using array module, all elements of the array must be of the same numeric
type.
import array as arr
a = arr.array(‘d’,[1.1 ,3.4 ,3.7 ,4.4]
41. Basic Data types and Operators
NUmbers are:
● int
● float
● Complex
sequence data types in Python are
● list
● String
● tuple
boolean data type and operators -- +, , /, *, % .
42. Conditionals
Python supports the usual logical conditions from mathematics:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
44. Loops
An "if statement" is written by using the if
keyword.
The elif keyword is pythons way of saying "if
the previous conditions were not true, then
try this condition".
45. Loops
With the while loop we can execute a
set of statements as long as a
condition is true.
46. Loops
A for loop is used for iterating over a
sequence (that is either a list, a tuple,
a dictionary, a set, or a string).
This is less like the for keyword in
other programming language, and
works more like an iterator method as
found in other object-oriented
programming languages.
With the for loop we can execute a set
of statements, once for each item in a
list, tuple, set etc.
47. Loops
With the break statement we can stop
the loop before it has looped through
all the items:
With the continue statement we can
stop the current iteration of the loop,
and continue with the next:
48. Loops
To loop through a set of code a
specified number of times, we can use
the range() function,
The range() function returns a
sequence of numbers, starting from 0
by default, and increments by 1 (by
default), and ends at a specified
number.
The range() function defaults to 0 as a
starting value, however it is possible
to specify the starting value by adding
a parameter: range(2, 6), which means
values from 2 to 6 (but not including
6):
49. Getting started with Tuples
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with
round brackets.
50. Dictionaries
A dictionary is a collection which is unordered, changeable and
indexed. In Python dictionaries are written with curly brackets, and they
have keys and values.
You can access the items of a dictionary by referring to its key name,
inside square brackets:
There is also a method called get() that will give you the same result:
You can change the value of a specific item by referring to its key
name:
Different function of adding and deleting
52. Sets
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
53. Getting started with Functions
A function is a block of code which only
runs when it is called.
You can pass data, known as
parameters, into a function.
A function can return data as a result.
function is defined using the def
keyword:
54. Advanced features of Functions
A lambda function is a small anonymous function.
A lambda function can take any number of
arguments, but can only have one expression.
Syntax :- lambda arguments : expression
The power of lambda is better shown when you use
them as an anonymous function inside another
function.
Say you have a function definition that takes one
argument, and that argument will be multiplied with
an unknown number: