CSCI 131 – Python Language



Python Language

• Emacs

• Input/Output Redirection

• Functions

Example 1:

• Create a directory BIO under your home directory. We will save all files in this directory. Type: mkdir BIO

• Change directory to your class directory, type the following on the Unix prompt: cd BIO

• Open a new file: emacs prog1.py &

• In the file prog1.py type the following program, including the comment lines

#In this example function has one numeric parameter and function has a return value

#function definition

def circleArea (radius):

area= radius *radius *3.14

return area

# main function that uses the function welcome

radius = 2.5

#function call inside print statement

print circleArea ( radius )

print circleArea ( 3.5)

radius = 4.5

#function call in assignment statement

areaResult = circleArea ( radius )

print areaResult

• Save your program

• Go to the login window and type the following on the Unix prompt:

o chmod u+x prog1.py

o python prog1.py

• Observe the result

Example 2:

• Open a new file: emacs prog2.py &

• In the file prog1.py type the following program, including the comment lines

#In this example function has one numeric parameter, function doesn’t have return value

#function definition

def mantra ( n ):

counter =0

while counter < n:

print “I love Python “

counter = counter +1

#main program

num = input (“please enter the number “)

print

print “the input value is “, num

#function call

print “the function result is “

print

mantra (num)

• Save your program

• Go to the login window and type the following on the Unix prompt:

o chmod u+x prog2.py

o python prog1.py

• Enter the input number after user prompt

• Observe the result

• Create a new file that will include the data, do the following:

o Type on the Unix prompt: emacs data &

o In the file type: 7

• Save the file and exit

• Go to the login window and type the following on the Unix prompt: python prog2.py < data

• Observe the result

• Go to the login window and type the following on the Unix prompt: python prog2.py < data > prog_result

• Open file with results by typing: emacs prog_result &

• Observe the results of the calculations

Examples 3 and 4 provide more information about the functions in Python. Type each program in the separate file and run the program to observe the results.

Example 3:

#In this example function doesn’t have any parameters, function doesn’t has return value

#function definition

def fiveStars ( ):

print “*****”

#main program

num = input ( “Please enter the number “)

counter =0

while ( counter < num ):

fiveStars ( )

counter = counter +1

Example 4:

#function definition

def scoreAlign (seq1, seq2):

i=0

sum=0

length=len(seq1)

while i ................
................

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

Google Online Preview   Download