pylecture4 -python basics2-
TRANSCRIPT
Write following python script with your text editor.
Then, run ‘python your_script.py’
If you got ‘Hello World’, go on to the next slide.
def main():
print ‘Hello World’
if __name__ == ‘__main__’:
main()
Lists – compound data type l = [1,2,3,5] # defines a list contains 1, 2, 3, 5
print l[0] # getting a value
l[0] = 6 # setting a value
l.append(7) # adding to list
print l # will print ‘[6, 2, 3, 5, 7]’
l.extend([8, 9, 10]) # connecting another list
print l # will print ‘[6, 2, 3, 5, 7, 8, 9, 10]’
print range(3) # stops at 2
print range(1, 3) # starts at 1 and stops at 2
print range(0, 5, 2) # start: 1 stop: 4 and steps by 2
Create following lists with range function.
1. [0, 1, 2, 3, 4]
2. [3, 4, 5, 6, 7]
3. [3, 6, 9, 12, 15, 18]
4. [2, 4, 6, 8, 12, 16, 20] hint: use + operator
Dictionaries – compound data type
Found in other languages as “map”, “associative memories”, or “associative arrays”
Lists vs Dictionaries › You can use only integer number as index on lists
Like a[0], a[-1]
› You can use integer numbers and strings as key on dictionaries(if its value exists)
Like d[0], d[‘foo’], d[‘bar’]
Creating a dictionary tel = {‘John’:8000, ‘Jane’:8001, ‘Joe’:8002}
Adding key and value tel[‘Joan’] = 8003 Getting value from key tel[‘Jane’]
Setting value from key tel[‘Joe’] = 0004 Removing value from key del tel[‘John’] Getting key list of a dictionary
tel.keys()
Crate a dictionary from two lists
names = [‘John’, ‘Jane’, ‘Joe’]
tel = [8000, 8001, 8002]
tel = dict(zip(names, tel))
Create a dictionary that
› Keys are [0, 1, …, 10]
› Values are (key) * 2
› i.e. d[0]=0, d[1]=2, d[2]=4, …, d[10]=20
Compares two values print 1 < 2 print 1 > 2
print 1 == 2
print 1 <= 2
print 1 >= 2
And, Or, and Not print 1 < 2 and 1 == 2
print 1 < 2 or 1 > 2
print not 1 == 2
x = int(raw_input(‘value of x: ’))
if x < 0:
print(‘x is negative’) # must indent
elif x > 0:
print(‘x is positive’)
else:
print(‘x is not positive neither negative’)
print(‘i.e. x is zero’)
For integer variable named ‘x’,
› Print ‘fizz’ if x can be divided by 3
› Print ‘buzz’ if x can be divided by 5
(e.g. if x is 10, print ‘buzz’, x is 15, print ‘fizz buzz’)
(hint: use % operator(e.g. 10 % 3 = 1, 14 % 5 = 4))
n = int(raw_input(‘list length: ’))
l = []
for i in range(n): # for each number in (0…n-1)
l.append(raw_input(‘%dth word: ’ % i))
for w in l: # for each word in your list
print w
Create a list only contains
› Multiple of 3 or 5 (3, 5, 6, 9…)
› Between 1 and 20
i.e. [3, 5, 6, 9, 10, 12, 15, 18, 20]
Find the 10-th Fibonacci sequence
› Fibonacci sequence is
0, 1, 1, 2, 3, 5, 8, …
The next number is found by adding up the two
numbers before it(e.g. 5th number 3 = 2 + 1).