python tricks cmsc 201. overview today we are learning some new tricks to make our lives easier!...

Post on 04-Jan-2016

212 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Python Tricks

CMSC 201

OverviewToday we are learning some new tricks to make our lives easier!

• Slicing and other tricks• Multiple return values• Global variables• Break and continue• Mutable and Immutable types• Try / Except

List Tricks

Negative IndexIf you want to get the last element of a list or string, you can use negative indices!

myString = “abcdef”print(myString[-1])print(myString[-2])

Prints:

fe

SlicingSay we have the string “My name is Max” and know, for some reason, that we want only the characters from index 3 to index 7.

myString = “My name is Max”slice = myString[3:7]

This is called string slicing! This will return the characters in myString from character 3 (inclusive) to 7 (exclusive). In this case, it prints the string “name”.

SlicingIf we leave off a number, it just goes to the end or beginning of the string!

myString = “abcdef”

print(myString[3:])

print(myString[:5])

Prints:

‘def’‘abcde’

SlicingWe can also control our step size.

myString = “abcdef”

print(myString[0:6:2])

Prints:

‘ace’

ExerciseWhat do the following print?

myString = “abcdef”

print(myString[:2])print(myString[1:3])print(myString[4:])print(myString[::2])

ExerciseWhat do the following print?

myString = “abcdef”

print(myString[:2])print(myString[1:3])print(myString[4:])print(myString[::2])

‘ab’‘bc’‘ef’‘ace’

List SlicingThis works for lists too!

myList = [1, 2, 3, 4, 5]

print(myList[3:])

Prints:

[4, 5]

Copying A ListWant a list full of zeroes?

myList = [0] * 3

print(myList)

[0, 0, 0]

Multiplying a list by something gives you that list, that many times!

print([1, 2, 3] * 2)

Prints:

[1, 2, 3, 1, 2, 3]

DangerRemember, lists are stored as references, so using the * operator on lists of lists is extremely dangerous!

myList = [1, [2, 3]] * 2

print(myList)

Prints:

[1, [2, 3], 1, [2, 3]]

DangermyList = [1, [2, 3]] * 2

print(myList)

Prints:

[1, [2, 3], 1, [2, 3]]

However, here’s what’s happening: [ , , , ]

1[2, 3]

Multiple Return Values

Multiple Return ValuesFunctions in python can return multiple things!

def myFunction(arg1, arg2):# Some stuff happens herereturn var1, var2, var3

def main():result1, result2, result3 = myFunction(1, 2)

Global Variables

Global VariablesEarlier in class we mentioned you can have global constants!

PI = 3.14

def area(radius):return PI * (radius ** 2)

These variables are visible anywhere in the program.

Global VariablesWhat happens here?

PI = 3.14

def area(radius):return PI * (radius ** 2)

def main():PI = 10print(PI)

This makes a new variable, also called PI, that lives in main. The original PI is unchanged. The new PI overshadows the old one.

Global Variables

PI = 3.14

def area(radius):print(PI)return PI * (radius ** 2)

def main():PI = 10print(PI)area(1)

Prints:103.14

Global VariablesIf you want to change a global variable (rather than making a new one), you must declare it as global.

PI = 3.14

def area(radius):print(PI)return PI * (radius ** 2)

def main():global PIPI = 10area(1)print(PI)

Global VariablesPI = 3.14

def area(radius):print(PI)return PI * (radius ** 2)

def main():global PIPI = 10area(1)print(PI)

Prints:

1010

Global Variables

Summary:

Global variables are visible anywhere in the program, but to change them, you have to put the global keyword in front of them first.

In this class, you should never need to do this.

Break and Continue

BreakSometimes, we want to get out of a loop before the termination condition.

Break immediately stops the loop!

Break

for i in range(0, 100):if i == 3:

breakprint(i)

print(“I have escaped the loop!”)

Prints:

012I have escaped the loop.

BreakBreak breaks out of whatever the innermost loop.

for j in range(0, 10):for i in range(0, 10):

if i == 3:break

print(i)

The break statement will stop the inner loop over and over, but not the outer loop.

ContinueContinue also changes how the loop works.

When a loop hits a continue statement, it immediately stops what it’s doing and goes back up to the next iteration of the loop.

for i in range(0, 5):if i == 3:

continueprint(i)

.

ContinueWhen a loop hits a continue statement, it immediately stops what it’s doing and goes back up to the next iteration of the loop.

for i in range(0, 5):if i == 3:

continueprint(i)

Prints:0124

Break and ContinueUsing break and continue correctly can be a bit complicated, so for this semester we ask that you not put them in your code!

Mutable vs. Immutable

Mutable vs. ImmutableThese are important vocab terms—a variable that is immutable can’t be changed without being reassigned (that is, you can’t change it without using the = operator).

a = 10a = 11

A mutable variable can have parts of it changed without being reassigned:

mylist = [1, 2, 3]myList[0] = 2

Notice that we only changed a part of it.

Mutable vs. Immutable

Mutable variables:

• Lists

Immutable variables:

• Float• String• Integer• Boolean

ReferencesThe way python stores information, each variable “points” to whatever value is in it. So when you say

a = 5

print(a)

Python has somewhere in the system that a variable called a points to 5.

a 5

Referencesa = 5

print(a)

So after setting a to 5, any time python goes to look up a, it finds 5.

a 5

If you reassign a, python changes what a points at. If you make two variables equal to 5, the both point at 5.

ReassignmentRemember this example?

a = 5b = aa = a + 1

When we change a, b doesn’t change, because there’s no connection to a. b points at the value 5, and so does a.

Since you can’t actually change 5, it doesn’t matter that they are pointing to the same thing.

a 5b a 6

Reassignment in FunctionsFunctions work the same way.

def someFunc(myVar):myVar = 10

def main():a = 5someFunc(a)print(a)

In this example, a just keeps pointing at 5

Notice that myVar and a both point to the number 5, there is just no way to change 5.

a 5

myVar myVar 10

ListsLists are different, because the thing they are pointing at is capable of changing!

a = [1, 2, 3]

b = a

a[1] = 10

print(b)

Prints:[1, 10, 3]

a [1, 2, 3]

b

a [1, 10, 3]

b

ListsWhat do we think this does?

def main():a = [1, 2, 3]myFunc(a)print(a)

def myFunc(myList):myList[1] = 100

ListsWhat do we think this does?

def main():a = [1, 2, 3]myFunc(a)print(a)

def myFunc(myList):myList[1] = 100

Prints [1, 100, 3]

a [1, 2, 3]

myList

Becomes:

a [1, 100, 3]

myList

ListsWhat about this?

def main():a = [1, 2, 3]myFunc(a)print(a)

def myFunc(myList):myList = [100]

ListsThe = operator changes what we’re pointing at.

def main():a = [1, 2, 3]myFunc(a)print(a)

def myFunc(myList):myList = [100]

Prints [1, 2, 3]

a [1, 2, 3]

myList

a [1, 2, 3]

myList [100]

top related