Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to CS Nov 21, 2016.

Similar presentations


Presentation on theme: "Intro to CS Nov 21, 2016."— Presentation transcript:

1 Intro to CS Nov 21, 2016

2 Today For loop and while loop List and string Dictionary

3 Looping if you know num_times
use for loop and range() for x in range(4) : print(“play song of Skyfall ….”) Use while loop c = 0: while c < 4 : print(“playing song of Skyfall…”) c = c + 1

4 Get the sum of numbers steps to compute the sum of integer from 1 to 4
sum = sum + 1 sum = sum + 2 sum = sum + 3 sum = sum + 4 Code for x in range(5) : sum = sum + x

5 Looping if you don’t know num_times
response = “” while reponse != ‘q’ : response = input(“ One more game? “) print(“starting next game….”) Note: this syntax is WRONG!!! while i in range(1,16,2): print (i)

6 Useful List methods momList = [‘apple’, ‘orange’, ’bread’]
dadList = [‘shovel’, ‘screw driver’] momList.append(‘milk’) # add a new item to the end momList.sort() # reorder and change the original list momList.sort(reverse=True) # sort in reverse order myString = ‘- ’.join(momList) # join all items with # ‘-’ as separator output: ‘apple-orange-bread’

7 Useful List operators momList = [‘apple’, ‘orange’,’bread’]
dadList = [‘shovel’, ‘screw driver’] family_list = momList + dadList # combine two lists print(family_list) output: ['apple', 'orange', 'bread', 'shovel', 'screw driver'] print(2*momList) # same as momList + momList output: ['apple', 'orange', 'bread', 'apple', 'orange', 'bread']

8 String myStr = ‘the ring’ index: 0 1 2 3 4 5 6 7
A special case of list. The item is one character. myStr = ‘the ring’ index: myStr[1] = ‘h’ myStr[7] = ‘g’ myStr[-1] = ‘g’ myStr[-4] = ‘r’

9 String slice and in operator
myStr = ‘the ring’ string slice myStr[start : stop : step] myStr[0:3] = ‘the’ myStr[4:] = ‘ring’ myStr[::] = ‘the ring’ myStr[::-1] = ‘gnir eht’ “in” operator ‘r’ in myStr # output: True

10 More string operators and methods
myStr = ‘the ring’ “+”: link two strings print(‘Lord of ‘ + myStr) output: Lord of the ring “*”: repeat string print(myStr*3) output: the ringthe ringthe ring

11 string split() myStr = ‘the ring’
Purpose: break a big string to a list of smaller strings syntax: myStr.split() # split with space as separator myStr.split(‘,’) # split with coma as separator wd_List = myStr.split() print(wd_list) # output: [‘the’, ‘ring’] Note: this is used in applications like google translate, or word frequency counting.

12 String looping myStr = ‘the ring’ count how many ‘e’ exists in myStr?
for char in myStr : if char==‘e’ : count = count + 1

13 Difference between list and string
momList = [‘apple’, ‘orange’] List is mutable. momList[1] = ‘grape’ #Item in a list can be changed. momList.sort() # list is changed in ascending order

14 Difference between list and string
name = ‘007 Spectre’ String is immutable. You can’t change any letter in a string. name[2] = ‘8’ # ERROR!!! A string method, such as name.upper(), will return a new string with uppercase. If you don’t assign the new string to a variable, it is gone. The original one always keeps the same. So, there is NOT name.sort() !!!!

15 Difference between list and string
s2 = '' for x in s1: if x!='5': s2 += x else: s2 += '6' print(s2) Difference between list and string name = ‘007 Spectre’ To change one or more letters in a string: create a new string, copy or add new letters one by one from the old one to the new one. name2 = ‘' for x in name: if x!=‘7': name2 += x else: name2 += ‘8' print(name2)

16 Dictionary In Python, a “dictionary” is a data container that stores multiple items of data as a list of key:value pairs The key:value pairs are unordered Values are referenced by their associated keys Key must be unique within a dictionary Key is typically a string name

17 Dictionary A dictionary in real world English  Spanish ‘one’  ‘uno’
‘two’  ‘dos’ Dictionary in Python: a data structure to associate two things to each other. Called “the key” and “the value”. A dictionary is a collection of key-value pairs. key: ‘one’ value: ‘uno’ key: ‘two’ value: ‘dos’

18 Dictionary eng2spa = {} # Create an empty dictionary
eng2spa[“one”] = “uno” # add or update entry print(eng2spa) # output: {'one': 'uno'} eng2spa[“two”] = “dos” #Add more entries. eng2spa[“three”] = “tres” print(eng2spa) # output: {'one': 'uno‘ , ‘two’ : ’dos’, ‘three’ : ‘tres’}

19 The reason to create dictionary: look up
Look up value by key eng2spa[‘one’] #output: uno Find out if a key exists in the dictionary: ‘two’ in eng2spa # output: True ‘five’ in eng2spa # output: False If you try to look up using a key that doesn’t exist, you get error. eng2spa[‘HiHiHi’] #KeyError

20 Other functions for dictionary
Len(eng2spa) # number of key-value pairs # output: 3 Get a list of keys key_list = list(eng2spa.keys()) for k in key_list: print(k) #output: [‘one’, ‘two’, ‘three’] Dictionary.values() returns a list with all values. val_list = list(eng2spa.values()) for v in val_list : print(v) #output: [‘uno’, ‘dos’, ‘tres’]

21 Dictionary and list list Use index to access list element.
List is ordered. You can order a list by calling myList.sort() Dictionary Use key to access value. Dictionary has no concept of order, so sorting a dictionary has no sense. If you print a dictionary a lot of times, you get different result. But, after you get key_list by calling list(dictionary.keys()), you can sort key_list.

22 Compare & Contrast

23 Empty myString ="" myList = [] myDict = {}

24 Creation myString = "This is a string. Easy to create"
myList = ['ab',3, 5,99, 'Leland'] myDict = { 4:23, 'mark': , 'mangiare': [1,2,3,'cc'] }

25 Access myString = "Oh say can you see" letter = myString[4] myList = [3,7, 'ppo', 99, 100] value = myList[ 3] myDict = {23:46, 'pi': , 'linda':'smith' } myDict['pi'] Must be an integer number Must be a key All use [ ] to access. Python Beauty!

26 Modify myString = "Oh sey can you see" myString[4] = 'a' illegal! Strings are immutable. Use myString.replace() myList = ['ab',3, 5,99, 'Leland'] myList[3] = 199 valid! Lists are mutable( only if the element exists ) myDict = { 4:23, 'mark': , 'mangiare': [1,2,3,'cc'] } myDict['mark'] = 'rich' valid! Overwrites current value myDict['albert'] = 'Einstein' valid! Creates a new key:value pair

27 How many myString = "This is a string. Easy to create"
len (myString) number of letters in the string myList = ['ab',3, 5,99, 'Leland'] len (myList) number of values in the list myDict = { 4:23, 'mark': , 'mangiare': [1,2,3,'cc'] } len (myDict) number of key-value pairs in dictionary


Download ppt "Intro to CS Nov 21, 2016."

Similar presentations


Ads by Google