Python Tricks
Download
Report
Transcript Python Tricks
Python Tricks
CMSC 201
Overview
Today 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 Index
If 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:
f
e
Slicing
Say 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”.
Slicing
If 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’
Slicing
We can also control our step size.
myString = “abcdef”
print(myString[0:6:2])
Prints:
‘ace’
Exercise
What do the following print?
myString = “abcdef”
print(myString[:2])
print(myString[1:3])
print(myString[4:])
print(myString[::2])
Exercise
What do the following print?
myString = “abcdef”
print(myString[:2])
print(myString[1:3])
print(myString[4:])
print(myString[::2])
‘ab’
‘bc’
‘ef’
‘ace’
List Slicing
This works for lists too!
myList = [1, 2, 3, 4, 5]
print(myList[3:])
Prints:
[4, 5]
Copying A List
Want 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]
Danger
Remember, 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]]
Danger
myList = [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 Values
Functions in python can return multiple things!
def myFunction(arg1, arg2):
# Some stuff happens here
return var1, var2, var3
def main():
result1, result2, result3 = myFunction(1, 2)
Global Variables
Global Variables
Earlier 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 Variables
What happens here?
PI = 3.14
def area(radius):
return PI * (radius ** 2)
def main():
PI = 10
print(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 = 10
print(PI)
area(1)
Prints:
10
3.14
Global Variables
If 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 PI
PI = 10
area(1)
print(PI)
Global Variables
PI = 3.14
def area(radius):
print(PI)
return PI * (radius ** 2)
def main():
global PI
PI = 10
area(1)
print(PI)
Prints:
10
10
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
Break
Sometimes, 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:
break
print(i)
print(“I have escaped the loop!”)
Prints:
0
1
2
I have escaped the loop.
Break
Break 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.
Continue
Continue 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:
continue
print(i)
.
Continue
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:
continue
print(i)
Prints:
0
1
2
4
Break and Continue
Using 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. Immutable
These 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 = 10
a = 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
References
The 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
References
a=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.
Reassignment
Remember this example?
a = 5
b = a
a = a + 1
a
b
a
5
6
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.
Reassignment in Functions
Functions work the same way.
def someFunc(myVar):
myVar = 10
myVar
def main():
a = 5
someFunc(a)
print(a)
a
myVar
10
5
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.
Lists
Lists are different, because the thing they are pointing at
is capable of changing!
a = [1, 2, 3]
a
b=a
b
[1, 2, 3]
a[1] = 10
a
print(b)
Prints:
[1, 10, 3]
b
[1, 10, 3]
Lists
What do we think this does?
def main():
a = [1, 2, 3]
myFunc(a)
print(a)
def myFunc(myList):
myList[1] = 100
Lists
What 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
Lists
What about this?
def main():
a = [1, 2, 3]
myFunc(a)
print(a)
def myFunc(myList):
myList = [100]
Lists
The = operator changes what we’re pointing at.
def main():
a = [1, 2, 3]
myFunc(a)
print(a)
def myFunc(myList):
myList = [100]
a
myList
a
myList
Prints [1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[100]