Download SEL2211: Coding Mini-Module Handout 2 More Basics: Lists

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
SEL2211: Coding Mini-Module
Handout 2
More Basics: Lists, Loops, and the like
April 28, 2017
Use this resource much more than any notes I give you (but be sure you know if
you’re looking at Python 2 or Python 3 docs):
https://docs.python.org/3/library/
If you are behind, or want to get ahead, or want to hear professionals introduce this
stuff, go through an online tutorial:
https://docs.python.org/3/tutorial/index.html
Or, there are online Python courses, like:
https://www.codecademy.com/learn/python
1
Data Structures: lists, dictionaries
1.1
lists
• lists are like variables of variables: they are a data structure containing an
ordered sequence of things.
mynewlist = [3454,234,634]
another = ["word","a","contains","this","thing"]
• You can refer to individual items in a list by using the index of the item in
the list, i.e. a number representing the position of the item in the order of the
list, starting with 0.
1.2 dictionaries
1 DATA STRUCTURES: LISTS, DICTIONARIES
• e.g. another[0] will return the string “word”. another[17] will return an
error.
• The function len(list ) will return the integer length of a list. It’s super
useful, especially in conjunction with loops!
• The function str.split(string ) takes a string, splits it apart on whitespace,
and returns a list with each non-whitespace part of the original string as a
member of the list, in order. It’s really cool!
• Note that you can have an integer variable serve as the index of a list. For example, if you have a counter variable, which is being updated for some purpose,
you can also use it to index variable items in a list e.g.: another[counter]
• Also, just like there are functions that are defined specifically on strings, or
on integers, etc., there are functions defined specifically on lists. You will find
the function append() particularly useful, if you are adding things to a list
dynamically, automatically in the course of a programme.
• You can also make multi-dimensional data structures by having a list of lists.
Think of this as like storing a chessboard, or a noughts and crosses game...in
order to retrieve an individual item, you’d then have to index the list, and then
index the sublist, e.g. another[0][7] would then return the 8th item in the
0th list inside the another list.
• There are lots of other built-in list operations and functions in the python
library documentation on the list class.
1.2
dictionaries
• A dictionary is like a list, except that it is not indexed by the integer position
of items in the dictionary, but rather by keys, which you determine. They
keys can be numbers, strings, whatever, but you decide what they are.
• For example, you can initialize a dictionary in this way:
myNewThing = {"fudgey":"bar", "hippie":"shit",8:"eight", "stelpa":"girl"}
• And then myNewThing["hippie"] will return shit, etc.
2
2 LOOPS
• Alternatively, you can just initialize an empty dictionary, and then indexing
with a new key and using = will automatically append a new item under that
key, e.g.:
myNewThing = {}
myNewThing["hippie"] = "shit"
2
Loops
• Loops allow you to repeat a subroutine a certain number of times, until a
particular condition is fulfilled.
• The most common types I use are while-loops and for-loops.
• A while-loop runs the subroutine while a certain condition is true, and then
stops once the condition becomes false (the truth of the condition is tested
before each new run of the loop).
• Note: every subroutine introducer ends with a “:” in Python, and then the
subroutine is indented.
• E.g.:
ii = 0
while ii < 100:
sys.stdout.write("Happy Days\n")
ii = ii+1
• The above loop will print out the string exactly 100 times, and then stop.
• You can also use boolean variables to constrain loops, by setting them to True
or False within the loop.
• for-loops do a subroutine for each item in a list, or other data structure.
Calling the loop itself creates a variable, which then takes on the identity of
each item in the data structure, such as thing in the example below.
3
2 LOOPS
• For example, imagine you have a preexisting list called myList, with 10 members in it. The following loop will print out every item in the list:
for thing in myList:
sys.stdout.write(thing)
• In the example, the for X in Y: part is necessary for-loop syntax, but the
other parts are data-structure names that you can choose. thing gets created
anew when the loop begins.
• Note that you can achieve the same result with a while-loop, which can be
preferable in certain cases:
ii = 0
while ii < len(myList):
sys.stdout.write(myList[ii])
ii = ii+1
• THINK ABOUT THE LOGIC OF THE ABOVE CODE UNTIL YOU GET
IT!
Task 2
a. Write a counting Loop using a while-loop, just to count up to 10.
b. Write a counting Loop using a for-loop, to count the number of items in some
list or dictionary.
(Anyone really geeking out could think about using a list of boolean variables to
count in binary...)
Task 3
Read a sentence into a variable, then use a list, loop, and counter to output the
sentence in reverse order to Standard Output.
4
5 REGULAR EXPRESSIONS
Task 4
Write a loop which prints out all numbers divisible by 5, testing for such a number
on every run of the loop, and then stops after it reaches 100.
Task 5
How would you design a loop that ran until the user inputted a certain, magic word?
3
More String Functions
• Almost anything you want to do with strings, you can find here (or roll your
own): https://docs.python.org/2/library/string.html#module-string
• I use string.split() and string.replace() the most.
4
More Input/Output: Standard Input/Output, and
Files
5
Regular Expressions
• Refer to this over and over again: re module: https://docs.python.org/2/
library/re.html#module-re
• re.search() and re.sub() are some functions I use most.
• I also use appropriately tricked out versions of the lines if re.search() !=
None: and while re.search() != None: quite a lot.
5