├── LICENSE.txt ├── README.md ├── code ├── 3Dcontour.py ├── 3Dline.py ├── 3Dquiver.py ├── 3Dscatter.py ├── 3Dsurface.py ├── 3Dwiremesh.py ├── Ex-class.py ├── Ex-class1.py ├── Keyword.py ├── ListMembers.py ├── bar.py ├── barh.py ├── contour.py ├── datetime.py ├── def-multi.py ├── fn-hello.py ├── fn-sq.py ├── ifelif.py ├── infinite-loop.py ├── input.py ├── log.py ├── namespace.py ├── objPlot.py ├── pie.py ├── plotHistogram.py ├── plotHistogramBins.py ├── ploterror.py ├── ploterror1.py ├── plotly.py ├── polar.py ├── pytha.py ├── rw.py ├── scatter.py ├── sqPlot0.py ├── sqPlot1.py ├── sqPlot2.py ├── sqPlot3.py ├── sqPlot4.py ├── subplot1.py ├── test.py ├── textPlot.py ├── twinx.py ├── while-else.py └── while.py └── contributing.md /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/intro-to-python-for-engineers-and-scientists/0dd3cf29f50272a6df5e2fc205f39424c081cb08/LICENSE.txt -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Introduction to Python for Engineers and Scientists*](http://www.apress.com/9781484232033) by Sandeep Nagar (Apress, 2018). 4 | 5 | [comment]: #cover 6 | 7 | 8 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 9 | 10 | ## Releases 11 | 12 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 13 | 14 | ## Contributions 15 | 16 | See the file Contributing.md for more information on how you can contribute to this repository. 17 | -------------------------------------------------------------------------------- /code/3Dcontour.py: -------------------------------------------------------------------------------- 1 | from mpl_toolkits.mplot3d import axes3d 2 | import matplotlib.pyplot as plt 3 | from matplotlib import cm 4 | import numpy as np 5 | 6 | fig = plt.figure() 7 | ax1 = fig.add_subplot(121, projection='3d') 8 | x = np.linspace(2*np.pi,-2*(np.pi),1000) 9 | y = np.linspace(2*np.pi,-2*(np.pi),1000) 10 | X,Y = np.meshgrid(x,y) 11 | Z = np.sin(X) + np.sin(Y) 12 | 13 | cont = ax1.contour(X, Y, Z) 14 | ax1.clabel(cont, fontsize=9, inline=1) 15 | ax1.set_xlabel('$x$') 16 | ax1.set_ylabel('$y$') 17 | ax1.set_title('Contour for $z=sin(x)+sin(y)$') 18 | 19 | ax2 = fig.add_subplot(122, projection='3d') 20 | Z = np.sin(X) + np.sin(Y) 21 | cont = ax2.contourf(X, Y, Z) 22 | ax2.clabel(cont, fontsize=9, inline=1) 23 | ax2.set_xlabel('$x$') 24 | ax2.set_ylabel('$y$') 25 | ax2.set_title('Filled Contour for $z=sin(x)+sin(y)$') 26 | 27 | 28 | 29 | plt.show() 30 | 31 | -------------------------------------------------------------------------------- /code/3Dline.py: -------------------------------------------------------------------------------- 1 | import matplotlib as mpl 2 | from mpl_toolkits.mplot3d import Axes3D 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | 6 | fig = plt.figure() 7 | ax = fig.gca(projection='3d') 8 | 9 | x = np.linspace(-10*(np.pi),10*(np.pi),10e4) 10 | y = np.sin(x) 11 | z = np.cos(x) 12 | 13 | ax.plot(x, y, z, label='$y=sin(x)$ and $z = cos(x)$') 14 | ax.legend() 15 | ax.set_title('3D line curve') 16 | ax.set_xlabel('$x$') 17 | ax.set_ylabel('$y = sin(x)$') 18 | ax.set_zlabel('$z = cos(x)$') 19 | plt.show() 20 | 21 | -------------------------------------------------------------------------------- /code/3Dquiver.py: -------------------------------------------------------------------------------- 1 | from mpl_toolkits.mplot3d import axes3d 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | x = np.linspace(np.pi,-(np.pi),10) 6 | y = np.linspace(np.pi,-(np.pi),10) 7 | (X,Y) = np.meshgrid(x,y) 8 | u = -15*X 9 | v = 5*Y 10 | q = plt.quiver(X,Y,u,v,angles='xy',scale=1000,color='b') 11 | #p = plt.quiverkey(q,1,16.5,50,"50 m/s",coordinates='data',color='r') 12 | xl = plt.xlabel("x (km)") 13 | yl = plt.ylabel("y (km)") 14 | plt.show() -------------------------------------------------------------------------------- /code/3Dscatter.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from mpl_toolkits.mplot3d import Axes3D 3 | import matplotlib.pyplot as plt 4 | 5 | fig = plt.figure() 6 | ax = fig.add_subplot(111, projection='3d') 7 | 8 | x = np.linspace(-5*(np.pi), 5*(np.pi),200) 9 | y =np.sin(x) 10 | z =np.cos(x) 11 | 12 | ax.scatter(x, y, z, marker='*') 13 | 14 | ax.set_xlabel('$x$') 15 | ax.set_ylabel('$y = sin(x)$') 16 | ax.set_zlabel('$z = cos(x)$') 17 | ax.set_title('Scatter plot in 3D') 18 | 19 | plt.show() 20 | 21 | -------------------------------------------------------------------------------- /code/3Dsurface.py: -------------------------------------------------------------------------------- 1 | from mpl_toolkits.mplot3d import axes3d 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | fig = plt.figure() 6 | ax = fig.add_subplot(111, projection='3d') 7 | 8 | a = np.arange(-5, 5, 0.25) 9 | b = np.arange(-5, 5, 0.25) 10 | x, y = np.meshgrid(a, b) 11 | z = np.sqrt(x**2 + y**2) 12 | 13 | ax.plot_surface(x, y, z, rstride=2, cstride=2) 14 | 15 | ax.set_xlabel('x') 16 | ax.set_ylabel('$y$') 17 | ax.set_zlabel('$z = \sqrt{x^{2}+y^{2}}$') 18 | ax.set_title('Surface type of 3D plot') 19 | 20 | plt.show() 21 | 22 | -------------------------------------------------------------------------------- /code/3Dwiremesh.py: -------------------------------------------------------------------------------- 1 | from mpl_toolkits.mplot3d import axes3d 2 | import matplotlib.pyplot as plt 3 | import numpy as np 4 | 5 | fig = plt.figure() 6 | ax = fig.add_subplot(111, projection='3d') 7 | 8 | a = np.arange(-5, 5, 0.25) 9 | b = np.arange(-5, 5, 0.25) 10 | x, y = np.meshgrid(a, b) 11 | z = np.sqrt(x**2 + y**2) 12 | 13 | ax.plot_wireframe(x, y, z, rstride=2, cstride=2) 14 | 15 | ax.set_xlabel('$x$') 16 | ax.set_ylabel('$y$') 17 | ax.set_zlabel('$z = \sqrt{x^{2}+y^{2}}$') 18 | ax.set_title('Wiremesh type of 3D plot') 19 | 20 | plt.show() 21 | 22 | -------------------------------------------------------------------------------- /code/Ex-class.py: -------------------------------------------------------------------------------- 1 | #Python code to explain defining 2 | #and using class 3 | 4 | #A class named python_program is defined 5 | class first_program: 6 | ''' 7 | This program has two methods: hi and hi_again 8 | ''' 9 | greeting = 'Hello Everybody\n' #Class variable definition 10 | 11 | #Now we define two instances of this class as "hi" and "hi_again" 12 | def hi(self): 13 | greet = 'Hello World!\n' 14 | print(greet) 15 | def hi_again(self): 16 | greet_again = 'Hello again!\n' 17 | print(greet_again) 18 | 19 | #Procedures to call the class 20 | 21 | x = first_program() # Calling the class 22 | print('The type of object storing class calling is:', type(x)) 23 | x.hi() #Calling an instance of "x" class 24 | x.hi_again() # Calling another instance of "x" class 25 | # Results of both instances depend on thier definitions 26 | 27 | #Acessing class variable 28 | #Class variable can be accessed from anywhere 29 | print(first_program.greeting) 30 | 31 | #Printing the documentation string 32 | print(first_program.__doc__) 33 | -------------------------------------------------------------------------------- /code/Ex-class1.py: -------------------------------------------------------------------------------- 1 | #Python code to show usage of __init__ 2 | 3 | # Defining a class "library" 4 | # which stores information about book's name and price 5 | 6 | #Defining class 7 | class library: 8 | 'The base class for all books' 9 | bookCount = 0 #Class variable setting count of books to zero 10 | 11 | def __init__(self, name, price):# Initializing the instance of class with name, price and updated book count 12 | self.name = name 13 | self.price = price 14 | library.bookCount += 1 15 | 16 | def displayCount(self): 17 | print("Total Employee %d",library.bookCount) 18 | 19 | def displayBook(self): 20 | print("Name : ", self.name, ", Price: ", self.price) 21 | 22 | #Creating objects 23 | 24 | book1 = library("Introduction to python",100) # First instance of object "library" 25 | print(type(book1)) 26 | 27 | book2 = library("Basic Python",150) # Second instance of object "library" 28 | print(type(book2)) 29 | 30 | book3 = library("Intermediate Python",200) # Third instance of object "library" 31 | print(type(book3)) 32 | 33 | book4 = library("Advanced Python",300) # Four instance of object "library" 34 | print(type(book2)) 35 | 36 | # Accessing attributes 37 | 38 | print("Details of first book:") 39 | book1.displayBook() 40 | 41 | print("Details of second book:") 42 | book2.displayBook() 43 | 44 | print("Details of third book:") 45 | book3.displayBook() 46 | 47 | print("Details of fourth book:") 48 | book4.displayBook() 49 | 50 | print("Total Number of books= %d" % library.bookCount) 51 | 52 | # Probing the bult-in attributes 53 | 54 | print("library.__doc__:", library.__doc__) 55 | print("library.__name__:", library.__name__) 56 | print("library.__module__:", library.__module__) 57 | print("library.__bases__:", library.__bases__) 58 | print("library.__dict__:", library.__dict__) 59 | -------------------------------------------------------------------------------- /code/Keyword.py: -------------------------------------------------------------------------------- 1 | import keyword 2 | 3 | print("Python keywords: ", keyword.kwlist) -------------------------------------------------------------------------------- /code/ListMembers.py: -------------------------------------------------------------------------------- 1 | #Python program to illustrate usage 2 | #of for loop 3 | a = ['a',1,3.14,'name'] 4 | 5 | for item in a: 6 | print("The current item is: ",item) -------------------------------------------------------------------------------- /code/bar.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.array([1,2,3,4,5,6,7,8,9,0]) 4 | y = np.array([1,4,2,3,4,5,7,6,8,7]) 5 | pl.bar(x, y) 6 | pl.title('Vertical Bar chart') 7 | pl.xlabel('$x$') 8 | pl.ylabel('$y$') 9 | pl.show() -------------------------------------------------------------------------------- /code/barh.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.array([1,2,3,4,5,6,7,8,9,0]) 4 | y = np.array([1,4,2,3,4,5,7,6,8,7]) 5 | pl.barh(x, y) 6 | pl.title('Horizontal Bar chart') 7 | pl.xlabel('$x$') 8 | pl.ylabel('$y$') 9 | pl.show() -------------------------------------------------------------------------------- /code/contour.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | # defining data for x, y, z axes 5 | x = np.linspace(0,1,100) 6 | y = np.linspace(1,2,100) 7 | (X,Y) = np.meshgrid(x,y) 8 | z = np.sin(X)-np.sin(Y) 9 | 10 | # plotting contour 11 | fig = plt.figure() 12 | 13 | ax1 = fig.add_subplot(211) 14 | c1 = ax1.contour(x,y,z) 15 | l1 = ax1.clabel(c1) 16 | lx1 = ax1.set_xlabel("x") 17 | ly1 = ax1.set_ylabel("y") 18 | 19 | 20 | # plotting filled contour 21 | ax2 = fig.add_subplot(212) 22 | c2 = ax2.contourf(x,y,z) 23 | l2 = ax2.clabel(c2) 24 | lx2 = ax2.set_xlabel("x") 25 | ly2 = ax2.set_ylabel("y") 26 | 27 | plt.show() 28 | 29 | # plotting filled contour -------------------------------------------------------------------------------- /code/datetime.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | from matplotlib.finance import quotes_historical_yahoo_ochl 3 | from matplotlib.dates import YearLocator, MonthLocator, DateFormatter 4 | import datetime 5 | date1 = datetime.date(1990, 1, 1) 6 | date2 = datetime.date(2015, 4, 12) 7 | 8 | years = YearLocator() # every year 9 | months = MonthLocator() # every month 10 | yearsFmt = DateFormatter('%Y') 11 | 12 | quotes = quotes_historical_yahoo_ochl('INTC', date1, date2) 13 | if len(quotes) == 0: 14 | raise SystemExit 15 | 16 | dates = [q[0] for q in quotes] 17 | opens = [q[1] for q in quotes] 18 | 19 | fig, ax = plt.subplots() 20 | ax.plot_date(dates, opens, '-') 21 | 22 | # format the ticks 23 | ax.xaxis.set_major_locator(years) 24 | ax.xaxis.set_major_formatter(yearsFmt) 25 | ax.xaxis.set_minor_locator(months) 26 | ax.autoscale_view() 27 | 28 | # format the coords message box 29 | def price(x): return '$%1.2f'%x 30 | ax.fmt_xdata = DateFormatter('%Y-%m-%d') 31 | ax.fmt_ydata = price 32 | ax.grid(True) 33 | 34 | fig.autofmt_xdate() 35 | plt.show() -------------------------------------------------------------------------------- /code/def-multi.py: -------------------------------------------------------------------------------- 1 | def sum(a,b): 2 | ''' 3 | sum() takes two inputs and produces 4 | a tuple of inputs and thier sum 5 | ''' 6 | c = a+b 7 | return a,b,c 8 | 9 | results = sum(100,102) 10 | print(results) -------------------------------------------------------------------------------- /code/fn-hello.py: -------------------------------------------------------------------------------- 1 | def greet(): 2 | ''' 3 | greet() just greets with the string 4 | "Hello World!" each time it is called 5 | ''' 6 | print("Hello world!") 7 | 8 | greet() -------------------------------------------------------------------------------- /code/fn-sq.py: -------------------------------------------------------------------------------- 1 | def square(x): 2 | ''' 3 | square() squares the input value 4 | One must only used numeric data types 5 | to avoid getting error 6 | ''' 7 | return x*x 8 | 9 | for i in range(10): 10 | squared_i= square(i) 11 | print(i, squared_i) 12 | -------------------------------------------------------------------------------- /code/ifelif.py: -------------------------------------------------------------------------------- 1 | # Program to calculate shipping cost based on money spent and location 2 | 3 | total = int(input('What is the total amount for your online shopping?\n')) 4 | area = input('''Type "I" if you are shopping within India... 5 | and "O" if you are shopping outside India\n''') 6 | 7 | if area == "I": 8 | if total <= 500: 9 | print("Shipping Costs INR 20.00") 10 | elif total <= 1000: 11 | print("Shipping Costs INR 100.00") 12 | elif total <= 1500: 13 | print("Shipping Costs INR 250.00") 14 | else: 15 | print("FREE") 16 | 17 | if area == "O": 18 | if total <= 500: 19 | print("Shipping Costs INR 75.00") 20 | elif total <= 1000: 21 | print("Shipping Costs INR 200.00") 22 | elif total <= 1500: 23 | print("Shipping Costs INR 500.00") 24 | else: 25 | print("FREE") -------------------------------------------------------------------------------- /code/infinite-loop.py: -------------------------------------------------------------------------------- 1 | # Program to define an infinite loop 2 | # Press Ctrl+C to interrupt execution of python REPL 3 | i=1 4 | while i==1: 5 | print(i) 6 | print("Good bye") -------------------------------------------------------------------------------- /code/input.py: -------------------------------------------------------------------------------- 1 | from_keyboard = input("Enter the input for input function:") 2 | print("input yields = ",from_keyboard) 3 | print(type(from_keyboard)) -------------------------------------------------------------------------------- /code/log.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | x = np.arange(0., 10, 0.01) 5 | 6 | fig = plt.figure() 7 | 8 | ax1 = fig.add_subplot(221) 9 | y1 = np.log(x) 10 | ax1.plot(x, y1); 11 | ax1.grid(True) 12 | ax1.set_ylabel('$y = log(x)$'); 13 | ax1.set_title('y-axis in log scale') 14 | 15 | ax2 = fig.add_subplot(222) 16 | y2 = np.sin(np.pi*x/2.) 17 | ax2.semilogx(x, y2, basex = 3); 18 | ax2.grid(True) 19 | ax2.set_title('x-axis in log scale') 20 | 21 | ax3 = fig.add_subplot(223) 22 | y3 = np.sin(np.pi*x/3.) 23 | ax3.loglog(x, y3, basex=2); 24 | ax3.grid(True) 25 | ax3.set_ylabel('both axes in log'); 26 | 27 | ax4 = fig.add_subplot(224) 28 | y4 = np.cos(2*x) 29 | ax4.loglog(x, y3, basex=10); 30 | ax4.grid(True) 31 | 32 | plt.show() -------------------------------------------------------------------------------- /code/namespace.py: -------------------------------------------------------------------------------- 1 | # Python code to demonstrate the concept 2 | # of namespace and scope 3 | i = 1 4 | 5 | def my_function1(): 6 | i = 2 7 | print("value of i in my_function()1 scope is", i ) 8 | 9 | def my_function2(): 10 | i = 3 11 | print("value of i in my_function()2 scope is", i ) 12 | 13 | print('value of i in global scope is', i ) 14 | my_function1() 15 | print('value of i in global scope is', i ) 16 | my_function2() 17 | print('value of i in global scope is', i ) -------------------------------------------------------------------------------- /code/objPlot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | fig = plt.figure() 3 | # variable fig stores "figure" instance 4 | ax1 = fig.add_subplot(221) 5 | # variable ax1 stores the subplot of figure at 1st place in 2 x 1 matrix 6 | ax1.plot([-1, 1, 4], [-2, -3, 4]); 7 | # ax1 iscalled and plot fucntion is given to it. 8 | # plot function carries two lists giving x and y axis points for graph 9 | ax2 = fig.add_subplot(222) 10 | ax2.plot([1, -2, 2], [0, 0, 2]); 11 | # same logic as for ax1 12 | ax3 = fig.add_subplot(223) 13 | ax3.plot([10, 20, 30], [10, 20, 30]); 14 | ax4 = fig.add_subplot(224) 15 | ax4.plot([-1, -2, -3], [-10, -20, -30]); 16 | plt.show() 17 | # show the figure on computer terminal -------------------------------------------------------------------------------- /code/pie.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.array([1,2,3,4,5,6,7,8,9,0]) 4 | label = ['a','b','c','d','e','f','g','h','i','j'] 5 | explode = [0.2, 0.1, 0.5, 0, 0, 0.3, 0.3, 0.2, 0.1,0] 6 | pl.pie(x, labels=label, explode = explode, shadow=True, autopct='%2.2f%%') 7 | pl.title('Pie Chart') 8 | pl.show() -------------------------------------------------------------------------------- /code/plotHistogram.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pt 2 | import numpy as np 3 | 4 | a = np.random.rand(50) 5 | pt.hist(a) 6 | pt.show() -------------------------------------------------------------------------------- /code/plotHistogramBins.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pt 2 | import numpy as np 3 | 4 | a = np.random.rand(50) 5 | pt.hist(a,25) # setting number of bins to 25 6 | pt.show() -------------------------------------------------------------------------------- /code/ploterror.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.arange(0, 4, 0.2) # generated data point from 0 to 4 with step of 0.2 4 | y = x*2 # y = e^(-x) 5 | err = np.array([ 0,.1,.1,.2,.1,.5,.9,.2,.9,.2,.2,.2,.3,.2,.3,.1,.2,.2,.3,.4]) 6 | pl.errorbar(x, y, yerr=err, ecolor='r') 7 | pl.title('Error bar chart with symmetrical error') 8 | pl.xlabel('$x$') 9 | pl.ylabel('$y$') 10 | pl.show() -------------------------------------------------------------------------------- /code/ploterror1.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.arange(0, 4, 0.2) # generated data point from 0 to 4 with step of 0.2 4 | y = x*2 # y = e^(-x) 5 | err_positive = np.array([ 0.5,.1,.1,.2,.1,.5,.9,.2,.9,.2,.2,.2,.3,.2,.3,.1,.2,.2,.3,.4]) 6 | err_negative = np.array([ 0.2,.4,.3,.1,.4,.3,.1,.9,.1,.3,.5,.0,.5,.1,.2,.6,.3,.4,.1,.1]) 7 | pl.errorbar(x, y, yerr=[err_positive, err_negative], ecolor='r') 8 | pl.title('Error bar chart with Asyymetric error') 9 | pl.xlabel('$x$') 10 | pl.ylabel('$y$') 11 | pl.show() -------------------------------------------------------------------------------- /code/plotly.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import plotly.plotly as py 3 | from plotly.graph_objs import * 4 | py.sign_in('username','APIkey') 5 | data = Data([Scatter(x=np.arange(100),y=np.random.randn(100),name='trace 0')]) 6 | fig = Figure(data=data) 7 | plot_url = py.plot(fig) 8 | -------------------------------------------------------------------------------- /code/polar.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | 4 | r = np.arange(0, 10.0, 0.1) 5 | theta = 2* np.pi * r 6 | 7 | pl.polar(theta, r, color ='g') 8 | pl.show() -------------------------------------------------------------------------------- /code/pytha.py: -------------------------------------------------------------------------------- 1 | # Program to generate even Pythagorean numbers 2 | # Pythagorean numbers are those numbers for which pythagorus equation stands true 3 | 4 | from numpy import sqrt 5 | n = input("Please input a maximum number:") # Asks user to input a number 6 | n = int(n)+1 # converts the values stored in variable n to integer data type and adds 1 so that computation can be done if user feeds 0 7 | 8 | # Two loops to define arrays for a and b for which c shall be computed 9 | for a in range(1,n): 10 | for b in range(a,n): 11 | c_square = a**2 + b**2 12 | c = int(sqrt(c_square)) # c is converted to an integer 13 | if ((c_square - c**2) == 0): # if square of a and square of b is equal to square of c then the result will be zero 14 | if (c%2 ==0): # checking if c is an even number 15 | print(a, b, c) -------------------------------------------------------------------------------- /code/rw.py: -------------------------------------------------------------------------------- 1 | # Open a new file in write-binary mode 2 | 3 | file1 = open("new.txt","wb"); 4 | 5 | # Write a string to the file 6 | 7 | file2 = file1.write("python\nPython"); 8 | 9 | # Open the file in read and write mode 10 | 11 | file3 = open("new.txt","r+"); 12 | 13 | # Read first five characters of the file 14 | 15 | char10 = file3.read(10); 16 | 17 | print "first ten characters of the file are:", char10 18 | 19 | # close the file 20 | 21 | file3.close(); 22 | 23 | # Check it the file has been closed 24 | print file3.closed -------------------------------------------------------------------------------- /code/scatter.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.random.rand(1000) 4 | y = np.random.rand(1000) 5 | pl.scatter(x,y) 6 | pl.title('Scatter Chart') 7 | pl.xlabel('$x$') 8 | pl.ylabel('$y$') 9 | pl.show() -------------------------------------------------------------------------------- /code/sqPlot0.py: -------------------------------------------------------------------------------- 1 | # Python code for plotting numbers 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | a = np.arange(10) 5 | plt.plot(a) 6 | plt.show() 7 | -------------------------------------------------------------------------------- /code/sqPlot1.py: -------------------------------------------------------------------------------- 1 | # Plotting number using pylab 2 | import numpy as np 3 | from matplotlib import pylab as pl 4 | x = np.linspace(0,100) 5 | y = x ** 2 6 | pl.plot(x,y) 7 | pl.show() -------------------------------------------------------------------------------- /code/sqPlot2.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from matplotlib import pylab as pl 3 | x = np.linspace(0,100) 4 | y1 = x ** 2 # y is square of x 5 | y2 = x ** 2.2 # y is x raised to power 2.2 6 | pl.plot(x,y1) 7 | pl.plot(x,y2) 8 | pl.show() -------------------------------------------------------------------------------- /code/sqPlot3.py: -------------------------------------------------------------------------------- 1 | # import pylab and numpy 2 | from matplotlib import pylab as pl 3 | import numpy as np 4 | 5 | # Create a figure of size 9x7 inches, 100 dots per inch 6 | pl.figure(figsize=(9, 7), dpi=100) 7 | 8 | # Create a new subplot from a grid of 1x1 9 | pl.subplot(1, 1, 1) 10 | 11 | # We wish to plot sin(x) and sin(2x) 12 | 13 | # first we define x- axis in terms of pi units 14 | 15 | X = np.linspace(-np.pi * 2, np.pi *2, 10e4, endpoint=True) 16 | 17 | ''' x-axis is defined from -2pi to 2pi with 10000 points 18 | where last point is also included''' 19 | 20 | S, S2 = np.sin(X), np.sin(2*X) 21 | 22 | # Plot sin(x) with a blue continuous line of width 1 (pixels) 23 | # labelled as sin(x) 24 | pl.plot(X, S, color="blue", linewidth=1.0, linestyle="-", label = "$sin(x)$") 25 | 26 | # Plot sine(2x) with a red continuous line of width 1 (pixels) 27 | # labelled as sin(2x) 28 | pl.plot(X, S2, color="red", linewidth=1.0, linestyle="-", label = "$sin(2x)$") 29 | 30 | # Set x limits from -2pi to 2.5*pi 31 | pl.xlim(-2* np.pi, 2.5* np.pi) 32 | 33 | # Set x ticks 34 | pl.xticks(np.linspace(-2.5 * np.pi, 2.5 * np.pi, 9, endpoint=True)) 35 | 36 | # Set y limits from 1.2 to -1.2 37 | pl.ylim(-1.2, 1.2) 38 | 39 | # Set y ticks 40 | pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) 41 | 42 | # Set the tile as 'Sine waves' 43 | pl.title('$sin(x)$ and $sin(2x)$ waves') 44 | 45 | # Setting label on x-axis and y-axis 46 | 47 | pl.ylabel('$sin(x)$ and $sin(2x)$') 48 | pl.xlabel('$x$') 49 | 50 | # Setting the grid to be ON 51 | pl.grid(True) 52 | 53 | # To show a legend at one corner for differentiating two curves 54 | pl.legend() 55 | 56 | # Show result on screen 57 | pl.show() 58 | -------------------------------------------------------------------------------- /code/sqPlot4.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pt 2 | import numpy as np 3 | pt.plot(np.arange(10)) 4 | pt.savefig('plot1.png') -------------------------------------------------------------------------------- /code/subplot1.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | 4 | x = np.arange(10) 5 | y1 = np.random.rand(10) 6 | y2 = np.random.rand(10) 7 | 8 | fig = pl.figure() 9 | 10 | 11 | ax1 = fig.add_subplot(221) 12 | ax1.plot(x,y1) 13 | 14 | ax2 = fig.add_subplot(222) 15 | ax2.scatter(x,y2) 16 | 17 | ax3 = fig.add_subplot(223) 18 | ax3.hist(y1) 19 | 20 | ax4 = fig.add_subplot(224) 21 | ax4.barh(x,y2) 22 | 23 | pl.show() -------------------------------------------------------------------------------- /code/test.py: -------------------------------------------------------------------------------- 1 | print 'Hello' 2 | -------------------------------------------------------------------------------- /code/textPlot.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as pl 2 | import numpy as np 3 | x = np.arange(0, 2*np.pi, .01) 4 | y = np.sin(x) 5 | pl.plot(x, y, color = 'r'); 6 | pl.text(0.1, -0.04, '$sin(0) = 0$') 7 | pl.text(1.5, 0.9, '$sin(90) = 1$') 8 | pl.text(2.0, 0, '$sin(180) = 0$') 9 | pl.text(4.5, -0.9, '$sin(270) = -1$') 10 | pl.text(6.0, 0.0, '$sin(360) = 1$') 11 | pl.annotate('$sin(theta)=0$', xy=(3, 0.1), xytext=(5, 0.7), arrowprops=dict(facecolor='green', shrink=0.05)) 12 | pl.title('Inserting text and annotation in plots') 13 | pl.xlabel('$theta$') 14 | pl.ylabel('$y = sin( theta)$') 15 | pl.show() -------------------------------------------------------------------------------- /code/twinx.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | x = np.arange(0., 100, 1); 5 | y1 = x**2; 6 | # y1 is defined as square of x values 7 | y2 = np.sqrt(x); 8 | # y2 is defined as square root of x values 9 | 10 | fig = plt.figure() 11 | ax1 = fig.add_subplot(111) 12 | ax1.plot(x, y1, 'bo'); 13 | ax1.set_ylabel('$x^{2}$'); 14 | ax2 = ax1.twinx() # twinx() function is used to show twinned x axes 15 | ax2.plot(x, y2, 'k+'); 16 | ax2.set_ylabel('$\sqrt{x}$'); 17 | ax2.set_title('Same x axis for both y values'); 18 | plt.show() -------------------------------------------------------------------------------- /code/while-else.py: -------------------------------------------------------------------------------- 1 | # Python program to explain usage of while-else loop 2 | i=0 3 | 4 | while i<=5: 5 | print(i) 6 | i=i+1 7 | else: 8 | print("the value now execeeds 5") -------------------------------------------------------------------------------- /code/while.py: -------------------------------------------------------------------------------- 1 | # Program demonstrating usage of while loop 2 | 3 | # Program to count number of steps and time taken for thier execution 4 | 5 | import time #This module is used for timing lines of codes 6 | import numpy as np 7 | 8 | i = 0 # initializing the counter 9 | while(i<10): # counter condition 10 | start = time.clock() # defining the variable which stores time.clock(value) 11 | print("Square root of %d = %3.2f:"%(i,np.sqrt(i))) # printing the number and its squareroot 12 | i=i+1 # incrementing the counter 13 | timing = time.clock() - start # prints time taken to execute two lines of code above 14 | print("Time taken for execution = %e seconds \n" % timing) 15 | 16 | print("The end") # signifies exiting the loop after condition is satisfied -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! --------------------------------------------------------------------------------