Presentation is loading. Please wait.

Presentation is loading. Please wait.

PH2150 Scientific Computing Skills

Similar presentations


Presentation on theme: "PH2150 Scientific Computing Skills"— Presentation transcript:

1 PH2150 Scientific Computing Skills
#Lecture 2: Common mistakes from the first PS # raw_input returns a string, some were using the int () constructor, which caused unexpected errors when running the code. C = raw_input (‘C=?’) # raw_input takes a string as argument C = float (C) # redefines C as a floating point number The function eval ( ) can be used to input an argument that is a string, and treat the string as if it was a Python expression. # Another error due to incorrectly defined type Y = 1/3 # returns 0, integer division Y = 1.0/3.0 # returns

2 PH2150 Scientific Computing Skills
Importing functions from Modules/Packages When you launch Canopy, Welcome to Canopy's interactive data-analysis environment! with pylab-backend set to: qt Type '?' for more information. import numpy import matplotlib from matplotlib import pylab, mlab, pyplot np = numpy plt = pyplot from IPython.display import display from IPython.core.pylabtools import figsize, getfigs from pylab import * from numpy import * This creates over a thousand names in the ‘namespace’, This can be modified from within Canopy in the dropdown menu: EDITPREFERENCES PYTHON

3 PH2150 Scientific Computing Skills
Importing functions from Modules/Packages In contrast, in a python module (*.py file, i.e the script that you are writing and saving), you must explicitly import every name which you use. This is much more robust, and since you are not constantly typing and retyping as you would do at the prompt, the extra typing is well worth it. We will have a quick look at the different ways of doing. import modulename e.g. import math # then you can use function by calling modulename.functionname() from modulename import functionname e.g. from math import sqrt # Explicitly import a function by its name also you to call the functionname() from modulename import * # imports all the functionnames from the module import modulename as alias A Module: A file containing Python definitions (functions, variables and objects) themed around a specific task. The module can be imported into your program. The convention is that all import statements are made at the beginning of your code.

4 PH2150 Scientific Computing Skills
Importing functions from Packages A Package: Is a set of modules or a directory containing modules linked through a shared theme. Importing a package does not automatically import all the modules contained within it. Some useful packages: SciPy (maths, science and enginering module), Numpy (Numerical Python for arrays, fourier transforms and more), matplotlib (graphical representation), mayavi (3D visualisation module in Enthought distribution) from PackageName import  specific_submodule import PackageName.submodulename as alias e.g. import matplotlib.pyplot as plt Then to use the function xlabel from matplotlib.pyplot to set the x-axis label: plt.xlabel(‘axis label’)

5 PH2150 Scientific Computing Skills
Importing functions from Packages If when running your script you get the error: ImportError: No module named [module/package name] And you are sure that you have made no errors in the package name, then you may need to install the package via the Canopy Package manager

6 PH2150 Scientific Computing Skills
Control Structures in Python In general, statements are executed sequentially, top to bottom. There are many instances when you want to break away from this e.g, Branch point: choose to go in one direction or another based on meeting some condition. Repeat: You may want to execute a block of code several times. Programming languages provide various control structures that allow for more complicated execution paths. Here we will focus on two such examples conditionals and loops: Will see the if, while and for statements and associated else, elif, range, break and continue commands

7 PH2150 Scientific Computing Skills
Control Structures in Python Variable type – Boolean (True or False) X=2  # assign the value 2 to the variable X X==3 # Is X equivalent to 3? Out[] False X==2 # Is X equivalent to 2? Out[] True != is not equal to operator. True if both the operands are not equal else False. > is greater than or equal to operator. True if the first operand is greater than the second operand. >= is greater than or equal to operator. True if the first operand is greater than or equal to the second operand. Similarly, < and <= are less than and less than or equal to operators. Combined with the logical operators and, or, not allows more complex conditional statements. Print ( X==2 and X<8) 

8 PH2150 Scientific Computing Skills
The if statement is used to check a condition: if the condition is TRUE, we run a block of statements (the if-block), else (FALSE) we process another block of statements (else-block) or continue if no optional else clause. if guess==number: #if followed by condition we are testing, colon indicates begin the if-block <Block of statements> # indent shows that you are in the if-block, when the block of statements is completed you will drop back into the main program. if guess==number: #if TRUE execute statements <Block of statements> # skips else else:#if FALSE executes the second block <Block of statements> # returns to main program after these statements. if guess==number: # <Block of statements>

9 PH2150 Scientific Computing Skills
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE.. if guess==number: #1st condition <Block of statements> # elif condition2: # checks for a 2nd condition which if TRUE runs second block of statements. elif condition3: # checks for a 3rd condition which if TRUE runs 3rd block of statements. elif condition4: # checks for a 4th condition which if TRUE runs 4th block of statements. else: # optional else if all above statements are FALSE

10 PH2150 Scientific Computing Skills
You may want to check for another condition after a condition resolves to TRUE. Here you can use the nested if construct. In a nested if construct, you can have an if...elif...else construct inside another if...elif...else if condition1: # <Block of statements> # runs statements then checks next if. if condition2: #checks for a 2nd condition which if TRUE runs second block of statements. <Block of statements> # elif condition3: # checks for a 3rd condition which if TRUE runs 3rd block of statements. else: # if condition 1 is TRUE, but 2 and 3 are FALSE. else: # optional else if condition 1 is FALSE

11 PH2150 Scientific Computing Skills
Loops: for loops are traditionally used when you have a piece of code which you want to repeat number of times. As an alternative, there is the while Loop, the while loop is used when a condition is to be met, or if you want a piece of code to repeat forever. for letter in 'Python': # loops for each character in string print 'Current Letter :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # loops for each element in list print 'Current fruit :', fruit for index in range(len(fruits)): # loops for each element in list print 'Current fruit :', fruits[index] FruitsA=[x for x in fruits if x[0]==‘a’] # returns [‘apple’]

12 PH2150 Scientific Computing Skills
Control Structures in Python: range() The range() function creates a list of numbers determined by the input parameters. range([start,] stop[, step]) -> list of integers When step is given, it specifies the increment (or decrement). >>> range(5) [0, 1, 2, 3, 4] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 2) [0, 2, 4, 6, 8] e.g. How to get every second element in a list? for i in range(0, len(data), 2): print data[i]

13 PH2150 Scientific Computing Skills
Loops: the while loop is used when a condition is to be met, or if you want a piece of code to repeat forever. while expression: #while TRUE execute block of statements <Block of statements> var = 1 while var == 1 : # This constructs an infinite loop num = raw_input("Enter a number :") print "You entered: ", num if num=='Q': # This gives a route out of loop print “Goodbye” break # break will terminate the loop

14 PH2150 Scientific Computing Skills
User defined functions: Section 7 def name (parameters,…,…): “”” documentation string””” <Block of statements>


Download ppt "PH2150 Scientific Computing Skills"

Similar presentations


Ads by Google