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:
- chmod u+x prog1.py
- 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 “the input value is “, num
#function call
print “the function result is “
mantra (num)
- Save your program
- Go to the login window and type the following on the Unix prompt:
- chmod u+x prog2.py
- 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:
- Type on the Unix prompt: emacs data &
- 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<length:
if seq1[i] == seq2[i]:
sum = sum + 1
i = i + 1
return sum
#main program
seq1=raw_input("Please enter the first seq ")
print "seq1 is ", seq1
seq2=raw_input("Please enter the second seq ")
print "seq2 is", seq2
print "the score is ", scoreAlign(seq1, seq2)