Introduction to Python


How to install Python on Linux
How to run a Python program
The basic of Python codes
Data expressions
Built-in functions in Python
Interactive input/output
Conditional statement for Python
Loop structure for Python
Creating your own functions
Python modules
Reading/writing files for Python
Error handling code
Object Oriented Programming (OOP)
Tkinter package for GNU programming

Creating your own functions

A method (function) can be created with "def" command as follows:
def greeting():
   print "How are you doing?"
$ How are you doing?
You can make a method that takes an argument:
def hello(name):
   print "Hello %s" %name
$ Hello Jack.
A method that takes more than one argument can be done as follows:
def hi(name,num):
   print "Hi %s " %name *num
$ Hi Steve! Hi Steve! Hi Steve!
After defining a function, you can operate it on a list.
def square(x):
   return x*x

print map(square, [1,2,5])
$ [1, 4, 25]
Instead of using the defined function, you can use 'lambda' as a nameless function. The above code can be rewritten as follows:
print map(lambda x: x*x, [1,2,5])
Let's define the following function:
def sign(n):
   if n>=0:
      return 1   # 1 is true.
      return 0:
An "if" statement also returns a boolean value.
y=input("Enter a value.")
if sign(y):
   print y, " is a positive value."
   print y, " is a negative value."
$ Enter a value. 8
$ 8 is a positive value.

The following code is to count words. The file, "", can be any text file in the same directory.
import string
def couwords(m):
   list = string.split(m)
   return len(list)

inp = open("","r")
tot = 0
for line in inp.readlines():
print "This file has %s word(s)." %tot
$ This file has 8 word(s).

Python has recursive call. By using it, you can create a function that calculates factorial without a for loop.
def facto(k):
     return 1
     return k*facto(k-1)

j = input('Type a positive integer.')
print result

Back to Electronics Page

Back to Hiro's Physics Main