Python – Week 3

Transcription

Python – Week 3
Python – Week 3
§ IPython
§ Strings
§ Operators and methods
§ Formatting
§ List
§ Slicing
§ Mutability vs. Immutability
§ Tuples
§ Dictionary
§ Exercises
§ Part of the SciPy family: NumPy, Matplotlib, pandas, sympy, scipy libs
§ Supports tab completion, visualisation, notebooks, etc.
§ Other cool stuffs I don’t know how to use
§ Install
sudo apt-get install ipython3
§ sudo pip install ipython3
§ Windows users can ask Cortana
§
§ Let’s have some fun
import this
§ this?
§ this??
§
§ Text
§ Single, double or triple quotes
‘He said, “Pizza is love”’
§ “She said, ‘Pizza is life’”
§
§ ‘’’ And they lived
§ Happily ever after ‘’’
§ “all pizza ” “is good” => ‘all pizza is good’
§ ‘two’ + ‘strings’ + ‘can’ + ‘join’ => ‘twostringscanjoin’ # concatenation
§ ‘MOAR!’ * 5 => ‘MOAR!MOAR!MOAR!MOAR!MOAR!’ # repetition
§ split, strip, center, count, find, join, len, lower, replace,…
§ Documentation (and IPython) are your new BFF
§ If it makes sense for a specific ‘type’ (more on that later), it will work in Python
§ Positioning
§
'{0}, {1}, {2}'.format(Small', ’Medium', ‘Large')
§ Name arguments
§
'Coors: {lat}, {long}'.format(lat='37.24N', long='-115.81W')
§ Separator
§
'{:,}'.format(1234567890)
§ Type formatting
§
“%s pizza better be %d slices” % (“My”, “12”)
§ Container for elements in order
§ Denoted by [ ]
§
pizza_types = [“Pepperoni”, “Cheese”, “Barbecue”, “Macaroni”]
§ Accessed by list[index] # index starts from 0
§
pizza_types[0] => “Pepperoni”
§ Index can be negative too
§
pizza_types[-1] => “Macaroni”
§ Methods
pizza_types.append(“tofu”)
§ pizza_types.<tab>
§
§ Iterate and search for memberships like a pythonista
§ for pizza in pizza_types:
§
print(“%s is the best pizza” % pizza)
§ if “tofu” in pizza_types:
§
print(“Vitaly, there’s something wrong with you!!”)
§ vowels = 0
§ for letter in “the quick brown fox jumps over the lazy dog”:
§
if letter in [“a”, “e”, “i”, “o”, “u”]:
§ vowels += 1
§ print(“There were %d vowels in the sentence” % vowels)
“Star_Wars”
S
t
a
r
_
W
a
r
s
0
1
2
3
4
5
6
7
8
-9 -8 -7 -6 -5 -4 -3 -2 -1
§ Slices return a part of the “type” from an index to another but not
including it
§
§
§
§
§
vowels = [‘a’, ‘e’, ‘i’, ‘o’, ‘u’]
vowels[1:4] => [‘e’, ‘i’, ‘o’] # Notice: no ‘u’
vowels[1:] => [‘e’, ‘i’, ‘o’, ‘u’] # You can leave the ranges
vowels[:-2] => [‘a’, ‘e’, ‘i’] Slices work for (almost) all types that support
indexing
“pizza”[2:4] => “zz”
§ [from:to]
§ [from:]
§ [:to]
§ [from:to:step]
§ Want to slice in reverse order? Do negative!
§
[-5:-3]
§ Reverse? [::-1]
§ Both lists and strings can be accessed by indices
my_pizza = pizza_types[0] => “Pineapple”
§ my_pizza[2] => “n”
§
§ Only lists can be changed
pizza_types[-1] = “Spinach and Feta Cheese”
§ my_pizza[0] = “D” # Fail
§
§ List elements can be changed because they are “mutable”
§ String elements cannot be changed because they are “immutable”
§ Immutable data structures are ‘fast, efficient and cool’. Ask any functional
programming aficionado.
§ Containers that (usually) represent a “record”
§ Represented by ( )
§ order = (“Pepperoni”, 15, “Tennessee Tech”, “Vitaly”)
§ Best use case – multiple return values
§
def divmod(x, y):
§ return x / y, x % y
§ That is a built-in function
§ Containers that are a key, value pairs
§ pizza = {“crust”: “thin”, “size”: “extra-large”}
§ pizza[“slices”] = 12
§ pizza[“toppings”] = [“sausage”, “mushroom”, “jalapeño”]
§ for key in pizza:
§
print(“%s : %s” % (key, pizza[key]))
§ The keys are “hashed”, so they have a very fast access time.
§ For k, v in pizza.items():
§
print(“%s : %s” % (k, v))
§ ROT13
man ascii
§ ord() and chr()
§ String methods and iteration
§
§ Batch Rename
sys.argv
§ glob
§ os.rename
§ Lists, string methods, and iteration
§
§ Word recurrence
§
String methods, lists and dictionaries