Python | Notes 2

/ 6 Aug 2013 /
just a 'couple' of notes from ncss ;)


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#       Two kinds of numbers
#There are two types of numbers in Python.
#Whole numbers (or integers) have the type 'int', and fractional or decimal numbers have the type 'float'.
#You can convert between types by casting using the 'int' and 'float' functions:
x = 3.5
print(x)    # 3.5
print(int(x))   # 3

#Notice that when you cast from a float to an int the result is truncated (not rounded like you are used to in maths).
#In Python 3, division alwats returns a float (even when both the original numbers are integers).
#For example:
correct = 12
total = 15
mark = correct/total
print(mark)    # 0.8
print(type(mark))   # <class 'float'>

#A float is returned even when the result is a whole number:
correct = 15
total = 15
mark = correct/total
print(mark)     # 1.0
print(type(mark))   # <class 'float'>
print()

#       Letters and Words
#String are a sequence of characters. String are enclosed in either single or double quotes.
#For example
print('Hello World')
print("Grok's World")

#If you need to escape a special character within a string, you can do it by using the backslash.
print('Grok\'s world')

#You can access a character by indexing or a sequence of characters by slicing:
hello = 'Hello World'
grok = "Grok's world"
print(hello[0], hello[-1], hello[6])
print(grok[5:9], grok[-5:], grok[:4])

#You can check wether a string occurs in another using 'in', for example:
hello = 'Hello World'
grok = "Grok's world"
print('World' in hello)
print('cat' in grok)

#Some of the arithmetic operators also apply to strings. Addition concatenates strings, and miltiplication
#duplicates the string:
print('Hello' + 'World')
print('Hello'*5 + 'World'*2)

#Finally, you can find the length of a string using 'len'
msg1 = 'Hello World'
print(len(msg1)) # 11
print()

#       Manipulating strings
#Strings come with a wide range builtin methods that allow you to manipulate
#and tansform the. We're going to give some examples of some of the most useful one here
#You can change the case of a string:
msg = 'Hello World'
print(msg.upper())
print(msg.lower())

#You can also check the case of a string using isupper and islower.
#You can replace substrings within a string:

msg = 'Hello World'
print(msg.replace('l', 'X'))

#And you can count how many times a substring appears within a string:

msg = 'Hello World'
print(msg.count('l'))
#Some other fun methods you might want to try are title, swapcase, startswith and endswith.
#Note that srings are immutable, meaning that once the strin is constructed, it cannot be modified.
#For example, you cannot change a character in an existing string by assigning a new character to a subscript:

msg = 'Hello World'
msg[0] = 'X'


#Instead, we'll have to creae a new string bu slicing ip the string and concatenating the pieces, and then
#assigning the result back to the original variable:

msg = 'Hello World'
msg = 'X' + msg[1:]
print(msg)

#       Making decisions
#To control the flow of a program we often we often need to make decisions depending on whether a
#particular condition is True or False. In Python we do this with if... elif... else.

#elif is an abbreviation for else and if together. It works like this:

x = 5
if x > 3:
    print('x is less than three')
elif x == 3:
    print('x is equal to three')
else:
    print('x is greater than three')

#You can test as many cases as you want by using multiple elif(s).
#You can nest if statement inside each other. For example, to do the above without using elif you can do:

x = 5
if x < 3:
    print('x is less than three')
else:
    if x == 3:
        print('x is equal to three')



#           Conditional expressions
#   Operation                   Operator
#   equal to                    ==
#   not equal to                !=
#   less than                   <
#   less than or equal to       <=
#   greater than                >
#   greater than or equal to    >=


#You can use a print statement to test these operators in conditional expressions:

x = 3
print(x < 10)
#This print True because x is less than three

x = 3
print(x > 10)
#This prints False because 3 is not greater than 10.


##You are at a bake sale and want to choose your cake carefully based on the value for money.
##All the cakes are the same height, but come in different sized square tins, marked by their side lengths.

# Enter your code for "Costly cake!" here.
cake_len = float(input('Cake 1 side length (cm): '))
cake_cost = float(input('Cake 1 cost ($): '))
cake1 = cake_cost / cake_len**2

cake2_len = float(input('Cake 2 side length (cm): '))
cake2_cost = float(input('Cake 2 cost ($): '))
cake2 = cake2_cost / cake2_len**2

cm1 = round(cake_len**2)
cm2 = round(cake2_len**2)

print('Cake 1 costs ${:.2f} per cm2 for {} cm2'.format(cake1, cm1))
print('Cake 2 costs ${:.2f} per cm2 for {} cm2'.format(cake2, cm2))

if cake1 < cake2:
    print('Get cake 1!')
elif cake2 < cake1:
    print('Get cake 2!')

    
#       Creating and modifying lists
#Lists can be constructed from an existing string using the list builtin function

print(list('Hamlet'))

#Alternatively, you can create a list by splitting a string:
line = "to be or not to be"
words = line.split()
print(words)

#Lists in Python are mutable which means their elements can be changed:
name = ['H', 'a', 'm', 'l', 'e', 't']
name[0] = 'Z'
print(name)

#You can use in to check if a word is in a list
line = 'to be or not to be'
words = line.split()
print('be' in words)
print('tree' in words)

#       Manipulating Lists
#There are various list methods that can be used to modify lists.
#The append method adds an item to the end of the list:

pets = ['dog', 'mouse', 'fish']
pets.append('cat')
print(pets)

#The sort method sorts the items in order, e.g. strings in alphabetical order and numbers in ascending order.
#The reverse method sorts the items in reverse order:

pets = ['dog', 'mouse', 'fish', 'cat']
pets.sort()
print(pets)
pets.reverse()
print(pets)

#You can create a string from list elements using the join string method:

pets = ['dog', 'mouse', 'fish', 'cat']
print(' '.join(pets))  # join on space
print('-'.join(pets))  # join on hyphen

#Note that the elements are joined by whatever character is in the string:
#a space (' ') in the first example, and a hyphen ('-') in the second.

#       Repeating things
#To iterate over a list or range of known length we typically use a for loop.
#This executes the indented block of code each iteration.
#For example, this program counts how many time the letter 'e'
#appears in each word:

colours = ['red','green','blue']
for w in colours:
  print(w, w.count('e'))

#To loop over a range of numbers you can use the range function.
#It takes three arguments: start, stop and step.
#For example, to loop from 0 to the length of a string, in steps of 2
#(in other words, print out every second letter in the string), you can do:

word = 'isotope'
for i in range(0, len(word), 2):
  print(i, word[i])

#       Repeating things (while)
#To iterate while some condition is True we use while loops.
#In this example we generate the Fibonacci numbers up to 10:

a, b = 0, 1
while b < 30:
    print(b)
    a, b = b, a + b

#Note that in this example the use of multiple assignment.
#The code a, b = 0, 1 sets the variable a to a value of 0 and b to 1

#A common use of while loops is reading input from the user until they write
#the correct answer.

guess = input("What's the password? ")
while guess != "Grok":
    guess = input("Nope! Try again: ")
print("You got it.")


#Dictionaries are a type of data structure in Python that store key: value pairs.
#In an English dictionary if you look up a word you see that word's definition.
#In a Python dictionary, looking up the key returns you the associated value.
#This is MY way of writing dictionaries (not really my way)
d = dict(
        DOG = 'bitch please'
        dog = 'someones calm!!!'
        this = 'is a dictionary....')
    )
f = input('sup:  ')
print(d[f])

#This example creates a small dictionary with silly definitions.
#The dictionary associates the key 'dog' with the value 'a barker'.
#A colon : is used to separate the keys and the values.
##Should always check if keyword is in dict BEFORE printing it.
#There are three key-value pairs (called items)
#in this dictionary, one for 'dog', 'cat' and 'bird'.
#Notice that when the dictionary is printed,
#the key-value pairs are in a different order.
#That's because dictionaries don't keep track of the order things are added
#(unlike a list) so you can't rely on them being in a particular order.

#You can add/change items in a dictionary:

animals = {'dog': 'a barker', 'cat': 'a meower', 'bird': 'a tweeter'}
# change cat definition:
animals['cat'] = 'a purrer'
# add a new definition for mouse:
animals['mouse'] = 'a squeaker'
print(animals)

#       Creating a dictionary from input
#One very common way of creating a dictionary is looping thougth a file
#or input from the user. We start with an empt dictionary and add
#key-value pairs. Here's an example:
phonebook = {}

line = input('Name and number: ')
while line:
    name, number = line.split()
    phonebook[name] = int(number)
    line = input('Name and number: ')
print(phonebook)

#Notice how we split each line of input using the string method split
#and then once we have each name and number we add an entry to the dictionary.


Write a program that reads lines of input from the user. An empty line signifies the end of the input. Once your program has read in all of the lines, it should print each line out in the original order with each word reversed in place.
Your program should work like this:
Line: the quick brown fox jumped over the lazy dogs
Line: colourless green ideas sleep furiously
Line: richard of york gave battle in vain
Line: 
eht kciuq nworb xof depmuj revo eht yzal sgod
sselruoloc neerg saedi peels ylsuoiruf
drahcir fo kroy evag elttab ni niav
 
 
Copyright © 2010 M(ath)+me, All rights reserved