Python Part 3 - kiwi.bridgeport.edu

[Pages:10]1

Python ? Part 3

Python Loops:

Sometimes, we need to loop over (or iterate) data items, so that we can process large amount of data. Python provides a "for loop" and a "while loop" for this purpose. For loop is used when we know in advance how many times we need to repeat the code in the loop, where as a while loop is used in those cases where the number of repetitions needed are not known and can vary.

Example:

sumn = 0 for i in range(0, 4):

sumn = sumn + i print('i =',i) print('sumn = ',sumn)

In the above code, the body of the loop (lines that are indented in the for loop and shown in bold, will be executed 4 times. The loop variable i will vary 0, 1, 2, 3. Note that, even though, we indicated range(0,4), in Python, the upper limit is always one less than what is specified. So in this, it will be 3 (instead of 4).

If you run the above program, you will see the following output:

If you are new to programming, try to carefully understand the output. Noe that the last print statement:

print(`sumn = `,sumn) is not indented in the loop, so it will be executed only when all iterations of the loop re done.

Similarly, there is a while loop. Here is an example:

sumn = 0 i= 0 while i < 4:

sumn = sumn + i print('i =',i) i = i + 1 print('sumn = ',sumn)

The above code produces the same output as the previous version with the for loop. Note that in a while loop, you have to initialize the loop variable yourself before you start the loop, and increment it inside the loop. Unlike a for loop which typically uses the range(start,end) to determine which value to start the loop at, and when to end, as well as to increment it by one each time as the loop executes. We can stop a for loop, or a while loop early, by checking a condition and putting a break statement, e.g., examine the following program. It exits the for loop when sumn becomes greater than 12.

2

sumn = 0 for i in range(0,10):

sumn = sumn + i print('i =',i) if sumn > 12:

break print('sumn = ',sumn)

Exercise: Modify the while loop code to produce the same output as the for loop by putting a break statement in it.

We can change the step size (i.e., how much to increment the loop variable) in a for loop as:

sumn = 0 for i in range(0,10,2): # 2 is step size

sumn = sumn + i print('i =',i) if sumn > 10:

break print('sumn = ',sumn)

The while loop version of the above program appears as:

sumn = 0 i= 0 while i < 10:

sumn = sumn + i print('i =',i) i = i + 2 if sumn > 10:

break print('sumn = ',sumn)

3

String processing in Python: Strings can be declared using either single or double quotes. \

character is used as an escape character similar to Java. For example, \n indicates new line, \t means tab. + can be used to catenate strings. * can be used to repeat strings e.g.,

y = 3 * `hello' will produce hellohellohello to be stored in y.

Two or more string literals are catenated e.g., z = `hello'+ `hi' will result in hellohi being stored in z.

Use triple quotes to break a string constant into multiple lines. msg = """Hello there

How are you"""

You can also use three single quotes.

upper and lower functions are available on a string e.g., s1 = "hello" s2 = s1.upper()

To search for a string in a bigger string, use the index or find method. s1 = "hello there how are you" pos = s1.find(`how') # will produce 12

T create a substring use index range e.g. s1 = `helllo' s2 = s1[0:3] # will produce hel

Split a string into parts: s3 = `hello there how are you' parts = s3.split(` `) # space is the separator character print(parts[2]) # will print how

Converting strings to numbers.

snum = "25" num1 = int(snum) print(num1)

snum2 = "25.5" num2 = float(snum2) print(num2)

Lists and Tuples in Python

Lists are declared using [ ] and Tuples are declared using ( ). Lists can grow in size while tuples are fixed sise.

fruits = ['apples', 'oranges', 'bananas', 'plums', 'pineapples'] pfruits = fruits[2:4] #print(fruits) for fr in pfruits:

print(fr)

4

del fruits[2] fruits.remove('oranges') fruits.append('kiwi') print(fruits + pfruits)

List Examples:

Create a Python project named ListTest. Type the following code in the ListTest.py (type up to a print statement and test it) and execute the program so that you can gradually see the results.

import sys import random

def main(): mydata = [] # creates an empty list mydata.append(5) mydata.append(10) mydata.append(15) print(mydata) mydata.pop(-1) # pop from the end print(mydata) mydata.append(20) mydata.pop(1) # pop at a position print(mydata) mydata.append(13) print(mydata) # use indexing to assign, or read the element at a particular position mydata[2] = 25

print(mydata) # lists can contain different data type elements mylist =['tennis', 'golf', 5000, 5.3] print(mylist) #-------------------count function on a list-----------# vowels list vowels = ['a', 'e', 'i', 'o', 'i', 'u'] # count element 'i' count = vowels.count('i') # print count print('The count of i is:', count) # count element 'p' count = vowels.count('p') # print count print('The count of p is:', count)

mydata2 = [9, 11, 8] # print(len(mydata2)) sum = 0 for i in range(0,len(mydata2)):

sum = sum + mydata2[i] print(sum)

maxnum = sys.maxsize # python 3 minnum = -sys.maxsize - 1 # find minimum of data testscores = [87, 67, 92, 79, 85, 61, 96]

5

minscore = maxnum # 100000 for i in range(0,len(testscores)):

if (testscores[i] < minscore): minscore = testscores[i]

print('min score = ',minscore)

maxscore = minnum # -100000 for i in range(0,len(testscores)):

if (testscores[i] > maxscore): maxscore = testscores[i]

print('max score =',maxscore)

maxs = max(testscores) # try min print('maxscore via max = ',maxs)

sum = 0 # will cause a problem when using the builtin function sum later for test in testscores:

sum = sum + test avg = sum/len(testscores) print('avg = ', avg) # round(avg,2) for printing to 2 decimal places

# another way to find average #avg2 = sum(testscores)/len(testscores) # make sure you comment out previous sum #print('avg2 = ',avg2) #-------------- in op.-----------------a_list = [5, 10, 15, 20, 25, 30] b = 17 if b in a_list:

print('b=',b,' is found in list') else:

print('b is not found in list')

#--------------list constructor-----------------frlist = list(("apple", "banana", "cherry")) # note the double round-brackets print(frlist) #---------------------range operations----------# list is changeable------fruits = [] # empty list fruits.append("apple") fruits.append("orange") fruits.append("plum") fruits.append("kiwi") fruits.append("mango") print(len(fruits)) for fr in fruits:

print(fr) print(fruits[-1]) # last item index = -1 print('-----------') print(fruits[0:]) # -1 = last, 2:4 (from 2 to 3), 2:-1 (from 2 to one before last),0: fruits[2] = 'banana' fruits[0:2] = ['strawberry','blueberry'] print(fruits) fruits.insert(1,'blackberry') print(fruits)

# combining two lists--------------

6

firstlist = ["apple", "banana", "plum"] tropical = ["mango", "pineapple", "papaya"] firstlist.extend(tropical) # can extend list with a tuple print(firstlist) firstlist.remove('pineapple') print(firstlist) firstlist.pop(2) # remove at a position print(firstlist) firstlist.clear() # you can also use del firstlist print('after clear : ',firstlist)

#----------index of an item in a list------------fruits = ["apple", "banana", "cherry", "kiwi", "mango"] pos = fruits.index('kiwi') # throws an error if not in list print('position of kiwi=', pos)

if __name__ == "__main__": sys.exit(int(main() or 0))

Tuples in Python:

Tuples are used to group related things. Tuples are declared using parenthesis. For example, a student's information can be expressed as a tuple.

s1 = (`Bill','Baker',1234,85,91) A field of a tuple can be accessed by indexing on the position of the item (similar to a list) as:

id = s1[2]

Some of the operations on a tuple are similar to the list. The following program presents a few examples related to tuples. Create a new Python project called TuplesTest. Then type the following code in the TuplesTest.py (type up to each print statement and test it).

import sys import math

def compute_circle_rectangle_area(radius, width, height): circle_area = math.pi * radius * radius rectangle_area = width * height return (circle_area, rectangle_area) # return a tuple

def main(): # tuples are unchangeable #--------------tuple----------------------# to group related items, or fields # tuple cannot be directly modified - tuple is immutable p1 = ('Bill',1234,'grad student','CS') #p1[1] = 1235 will give an error # use type to determine the data type of any object print(p1[1])

p1list = list(p1) # to convert tuple to a list #p1list.pop(1) # remove item at position 1 p1list[1] = 1235 p1 = tuple(p1list) # to convert list to a tuple print(p1)

7

#----loop over tuple----for x in p1:

print(x)

for i in range(len(p1)): print(p1[i])

#-----------------------

result = compute_circle_rectangle_area(5,7,8) carea = result[0] carea, rarea = result # unpack tuple print(carea)

a_tuple = (5, 15, 20, 25, 30) b = 15 if b in a_tuple:

print('b=',b,' is found in tuple') else:

print('b is not found in tuple')

# --------------join tuples--------------tuples1 = ("Bill", "Baker" , 1234) tuples2 = (85,89, 85) tuples = tuples1 + tuples2 print(tuples)

#--------------count method for tuple - number of times an item occurs count85 = tuples.count(85) print('count 85 occurs = ', count85)

#-----------------index method to search for the position----pos = tuples.index("Baker") print("position of Baker = ", pos)

if __name__ == "__main__": sys.exit(int(main() or 0))

File Processing and Creating Classes in Python

In Python, the general statement for file processing starts by creating a file object as:

fobj = open(filename, mode)

The mode can be one of the following values. Default is read mode.

'r' read mode 'w' write (warning: existing file will be overwritten) 'a' append mode (appends at the end) 'r+' for both reading and writing.

8

Example : Read contents of a text file and print it to the console. Suppose you create a text file with student test scores as:

12341 Bill Baker 85 91

12342 Sally Simpson

92 88

12343 John Jacobs 80 77

Save the file in a folder e.g., c:\CPSC442\Data folder.

Create a new Python project called FileProcessing.

Type the following code in FileProcessing.Py file.

import sys

def display_file(): fobj = open("c:/CPSC442/Data/Students.txt","r") for line in fobj: print(line)

def main(): display_file()

if __name__ == "__main__": sys.exit(int(main() or 0))

If you run the program, it will display the contents of the file.

For writing to files, use write method that accepts a string as a parameter. Make sure to call close at the end via the file object. Example: Write the same data as read from the Students.txt file to Students2.txt file.

def copy_file(): fobj = open("c:/CPSC442/Data/Students.txt","r") fobj2 = open("c:/CPSC442/Data/Students2.txt","w") for line in fobj: print(line) fobj2.write(line) fobj2.write("12344" + "\t" + "Cindy" + "\t" + "Corman" + "\t" + "93" + "\t" + "89") fobj2.close()

Example: Read the data in Students.txt file and assign grades to the students. The assigned grades are to be written in another file called StudentGrades.txt with id, lastname and grade in each line.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download