Intro to CS Nov 21, 2016.

Slides:



Advertisements
Similar presentations
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Guide to Programming with Python
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Guide to Programming with Python
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 7 Lists and Tuples. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Data Structures.
Lists and Tuples Intro to Computer Science CS1510 Dr. Sarah Diesburg.
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.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Lecture 9 For Loops.
CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES.
Strings … operators Up to now, strings were limited to input and output and rarely used as a variable. A string is a sequence of characters or a sequence.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
More Python Data Structures  Classes ◦ Should have learned in Simpson’s OOP ◦ If not, read chapters in Downey’s Think Python: Think like a Computer Scientist.
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 17, 2016.
Python unit_4 review Tue/Wed, Dec 1-2
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
Generating Random Numbers
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
Announcements Project 4 due Wed., Nov 7
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Strings Part 1 Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Lists in Python.
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CHAPTER THREE Sequences.
Guide to Programming with Python
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Introduction to Python: Day Two
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Intro to Computer Science CS1510 Dr. Sarah Diesburg
For loops Taken from notes by Dr. Neil Moore
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Python Sets and Dictionaries
Python Review
Intro to Computer Science CS1510 Dr. Sarah Diesburg
CSE 231 Lab 6.
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Strings Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Dictionary.
Introduction to Computer Science
Presentation transcript:

Intro to CS Nov 21, 2016

Today For loop and while loop List and string Dictionary

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

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

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)

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’

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']

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: 0 1 2 3 4 5 6 7 -8 -7 -6 -5 -4 -3 -2 -1 myStr[1] = ‘h’ myStr[7] = ‘g’ myStr[-1] = ‘g’ myStr[-4] = ‘r’

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

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

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.

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

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

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() !!!!

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)

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

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’

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’}

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

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’]

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.

Compare & Contrast

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

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

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

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': 3.14159, 'mangiare': [1,2,3,'cc'] } myDict['mark'] = 'rich' valid! Overwrites current value myDict['albert'] = 'Einstein' valid! Creates a new key:value pair

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': 3.14159, 'mangiare': [1,2,3,'cc'] } len (myDict) number of key-value pairs in dictionary