9
MECN2012: Computing Skills and Software Development Lecture 17: Python - More Lists and Functions 1

Lecture+17+-+More+Lists+and+Functions

  • Upload
    ali-gh

  • View
    212

  • Download
    0

Embed Size (px)

DESCRIPTION

f

Citation preview

Page 1: Lecture+17+-+More+Lists+and+Functions

1

MECN2012: Computing Skills and Software Development

Lecture 17:Python - More Lists and Functions

Page 2: Lecture+17+-+More+Lists+and+Functions

2

More on Lists• Lists are general purpose and can contain any python objects.

numList = list(range(0, 8))evenList = []

for i in numList: evenList.append(2*i)

print("numList:", numList)print("evenList:", evenList)

sentence = "The name is Bond, James Bond"clauses = sentence.split(",")print("clauses:", clauses)

words = sentence.split(" ")print("words:", words)reply = "Good evening Mr " + words[-1] # access last entry of the listprint("reply:", reply)

numList: [0, 1, 2, 3, 4, 5, 6, 7]evenList: [0, 2, 4, 6, 8, 10, 12, 14]clauses: ['The name is Bond', ' James Bond']words: ['The', 'name', 'is', 'Bond,', 'James', 'Bond']reply: Good evening Mr Bond

Convert the range object into a list

Creates a list by separating the string wherever it finds a comma.

Page 3: Lecture+17+-+More+Lists+and+Functions

3

More on Lists• You can also create lists of lists to generate a matrix.

matrix = [[5,3,5], [3,4,9], [2,6,7]] # a nested list of listsprint("matrix:", matrix)print("matrix[2]:", matrix[2]) # access 3rd entry of the list print("matrix[1][0]:", matrix[1][0])

del matrix[1] # remove second entryprint("reduced matrix:", matrix)matrix.insert(1, [9,9,9]) # insert a new second rowprint("new matrix:", matrix)

matrix: [[5, 3, 5], [3, 4, 9], [2, 6, 7]]matrix[2]: [2, 6, 7]matrix[1][0]: 3reduced matrix: [[5, 3, 5], [2, 6, 7]]new matrix: [[5, 3, 5], [9, 9, 9], [2, 6, 7]]

Page 4: Lecture+17+-+More+Lists+and+Functions

4

1 2 3 4 5

ReferencingA = [1, 2, 3, 4, 5]B = Aprint("A:", A)print("B:", B)

B[2] = 999B = [9.9, 8.8, 7.7]C = Aprint("A:", A)print("B:", B)print("C:", C)

A: [1, 2, 3, 4, 5]B: [1, 2, 3, 4, 5]A: [1, 2, 999, 4, 5]B: [9.9, 8.8, 7.7]C: [1, 2, 999, 4, 5]

B

A

9.9 8.8 7.7

1 2 999 4 5

C

• When a non-primitive object is assigned to a variable, only a reference to the original object is copied. This is known as aliasing.– Faster– More memory efficient.

Connection is broken

Page 5: Lecture+17+-+More+Lists+and+Functions

5

1 2 3 4 5

Referencing• You can copy the actual values using slice referencing. This is called a deep copy.

# now do a deep copyA = [1, 2, 3, 4, 5]B = A[:] # copy each element one at a timeprint("A:", A)print("B:", B)

B[2] = 999print("B:", B)

B = [9.9, 8.8, 7.7]C = Aprint("A:", A)print("B:", B)print("C:", C)

B

A

9.9 8.8 7.7

1 2 3 4 5

C1 2 999 4 5

A: [1, 2, 3, 4, 5]B: [1, 2, 3, 4, 5]B: [1, 2, 999, 4, 5]A: [1, 2, 3, 4, 5]B: [9.9, 8.8, 7.7]C: [1, 2, 3, 4, 5]

Connection is broken

Page 6: Lecture+17+-+More+Lists+and+Functions

6

Functions• Programs are usually more useful and easier to understand if a modular

approach is used.

• We can remove a block of code and replace it with a call to a function that does the same thing.

• A function has the following form:

def FunctionName (transferred variables):statementsreturn returnedVariable

• E.g. def powerFunc(x, n): y = 1 for i in range(n): y = y*x

return y

Called the argument list

These values are sent to powerFunc when it is called

This is what will be sent back to the call

Page 7: Lecture+17+-+More+Lists+and+Functions

7

Functionsimport math

def circleArea(dia): Area = math.pi*dia*dia/4 return Area

def tubeVolume (di, do, L): Vol = (circleArea(do) - circleArea(di))*L return Vol

# start of main codeID = float(input("enter inner diameter: "))OD = float(input("enter outer diameter: "))length = float(input("enter cylinder length: "))

XsectnArea = circleArea(OD) - circleArea(ID) # outer area – inner area

print("cross-sectional area = ", XsectnArea)print("total volume of hollow shaft = ", tubeVolume(ID, OD, length))

Any function can call any other function, as long as it is defined

Function calls

Page 8: Lecture+17+-+More+Lists+and+Functions

8

Variable Scope• A local variable exists only within the function in which it was declared.

This function is referred to as the variable’s scope.

def factoFunc (n): if n == 0: n = 1 else: for i in range(n-1, 1, -1) : n = n*i

print("in factorial n = ", n)

funcVar = n

return n

n = int(input("enter an integer: "))

print("n! =", factoFunc(n))print("in main body of code n =", n)print("in main body of code funcVar =", funcVar)

enter an integer: 5in factorial n = 120n! = 120in main body of code n = 5Traceback (most rec… File "C:\... print("in main body …NameError: name 'funcVar' is not defined

This n is only defined in factoFunc

The n in the main code is a different variable. Only the value is passed when factoFunc is called. The value of n in the main code remains unaffected.

Page 9: Lecture+17+-+More+Lists+and+Functions

9

Functionsdef convert_mileh_2_ms (x): x = x*0.44704 return x

def convert_tonne_2_kg (x): x = x*1000 return x

speed = float(input("enter crash speed [mile/h]: "))mass = float(input( "enter vehicle mass [tonne]: "))

speed = convert_mileh_2_ms(speed) # convert to SI unitsmass = convert_tonne_2_kg(mass)

crashEnergy = 0.5*mass*speed*speed/1000 # E = 1/2*m*v^2 [kJ]

print( "speed =", speed, "m/s" )print( "mass =", mass, "kg" )print( "crash energy =", crashEnergy, "kJ" )

These x’s are different and only exist within their functions

These functions change the value of the variables.