Download presentation
Presentation is loading. Please wait.
1
Survey of Computer Science CSCI 110, Spring 2011 Lecture 8 Strings, Lists For Loops
2
Generating Random Numbers
Python provides libraries of functions that perform useful tasks. One of these libraries allows us to generate random numbers. To use the library, we must first import it: import random #This should be at the beginning of #the program To generate a random integer between 0 and x-1: myNumber = random.randrange(x) To generate a random number between low and high - 1: myNumber = random.randrange(low, high) Examples: points = random.randrange(10) #random number between 0 and 9 target = random.randrange(2, 11) #random number between 2 and 10
3
Example using random # Program: points.py
# Purpose: Generate random numbers of points import random # import library for random numbers count = 0 while count < 10: points = random.randrange(1, 11) print "You got", points, "points!" count = count + 1 #What is the output?
4
Collections Python provides several classes called collection that allow us to group data together. Sequential Collections: Strings--A sequential collection of characters Lists--A sequential collection of python objects Tuples--A specialized list whose items cannot be modified. Non-sequential Collections: Dictionaries-- Nonsequential collections of pairs of items. Each pair has a key and a value. The key can be used to look up the value.
5
Recall Strings A string is a sequential collection of characters.
The value of a string is given within quotes: "dog" "alpha centauri" "$37.62" Each character in a string can be accessed by its position. >>> monster = "fire-breathing dragon" >>> monster[0] 'f' >>> monster[2] 'r'
6
Things we can do with Strings
Operation Operator Example Concatenation "my " + "goodness" -> "my goodness" Repetition * "ha" * 3 -> "hahaha" Length len len("fire") -> 4 Substring [ : ] monster[1:4] -> "ire" # monster = "fire-breathing dragon" Membership in "ir" in monster -> True "w" in monster -> False
7
Other Methods with Strings
Object: A member of a class Method: An action the object can take To have an object carry out a method, we use "dot notation" myObject.methodName( ) myString.count(item) #number of occurrences of item in #myString Example: >>> monster = "troll" >>> monster.count("l") 2 >>> monster.count("rol") 1
8
More String Methods myString.upper( ) #returns a string with all upper case myString.lower( ) #returns a string with all lower case myString.find(substring) #returns index of 1st occurrence of #substring, or -1 if not found Examples: >>> monster = "troll" >>> monster.upper( ) "TROLL" >>>monster "troll" >>> monster.find("ll") 3
9
Lists A list is a sequential collection of python objects.
A list is written as a set of objects separated by commas,within square brackets: [1, 5, 7] ["dog", "cat", "bird"] [3.7, "spam", 46] [ ] We can access an element of a list by its position: Example: >>>inventory = ["Axe", "gold coins", "torch"] >>>inventory[2] "torch"
10
Things we can do with Lists
Operation Operator Example Concatenation [4.5, "Mary"] + [6, 2] -> [4.5, "Mary", 6, 2] Repetition * ["house"] * 3 -> ["house", "house", "house"] Length len inventory = ["Axe", "gold coins", "torch"] len(inventory) -> 3 Sublist [ : ] prices = [2.98, 5.67, 1.36, 14.92] prices[1:3] -> [5.67, 1.36] Membership in in prices -> True
11
Changing an item in a list
A list is stored in memory as a set of sequential id's referencing objects. alist = [3, "dog", "purple", 5.6] id id id id 3 "dog" "purple" 5.6 alist We can use indexing to assign a new value to any item in the list: >>> alist[2] = 6.7 >>> alist [3, "dog", 6.7, 5.6] Note: You cannot change a character in a string this way.
12
More fun with lists alist.append(item) #adds item to the end of the list alist.insert(i, item) #inserts item at the ith position in list alist.pop(i) #removes and returns the ith item alist.sort( ) #Sorts the list alist.reverse( ) #Reverses the list alist.index(item) #Returns the index of the 1st #occurrence of item alist.count(item) #Returns the number of occurrences #of item alist.remove(item) #Removes 1st occurrence of item
13
Some List examples >>> inventory = ["Axe", "Gold", "Torch"]
>>> inventory.append("Matches") >>> inventory ["Axe", "Gold", "Torch", "Matches"] >>> inventory.index("Gold") 1 >>> inventory.sort( ) ["Axe", "Gold", "Matches", "Torch"]
14
for loops A for loop allows us to perform an operation on each item in a list (or for each character in a string). Example: myString = "apple" for i in myString: print i print "done" Output: a p l e done
15
General form of a for loop
The general for of a for loop in python is: for myVar in myList: Python code Execution of a for loop: Assign the first item of the list (index 0) to myVar Execute the body of the loop Assign the second item of the list (index 1) to myVar Repeat for each consecutive item in the list (in order).
16
Another for loop example
# Use a for loop to add the numbers in a list: total = 0 prices = [2.75, 1.22, 4.16] for x in prices: total = total + x print total # What is the output? # We will work through the execution in class.
17
Generating a list of numbers
We often want to perform an operation some number of times, or use sequential numbers in our loop. To do this, we can use a for loop with a list of integers. We can generate the list of integers using the range( ) function. range(N) # Generates a list from 0 to N-1 range(start, stop) #Generates a list from start to stop - 1 range(start, stop, step) #Generates a list from start to stop - 1 #with step size given by step. Examples: >>> range(8) [0, 1, 2, 3, 4, 5, 6, 7] >>> range(4, 10) [4, 5, 6, 7, 8, 9] >>> range(3, 15, 2) [3, 5, 7, 9, 11, 13]
18
Examples Example 1: sum = 0 for i in range(1, 5): sum = sum + i
print sum # What is the output? Example 2: for i in range(5): print "Hurray!"
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.