Introduction to Python


Contents

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?"
greeting()
$ How are you doing?
You can make a method that takes an argument:
def hello(name):
   print "Hello %s" %name
hello("Jack.")
$ 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!",3)
$ 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.
   else:
      return 0:
An "if" statement also returns a boolean value.
y=input("Enter a value.")
if sign(y):
   print y, " is a positive value."
else:
   print y, " is a negative value."
$ Enter a value. 8
$ 8 is a positive value.


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

inp = open("test.py","r")
tot = 0
for line in inp.readlines():
   tot=tot+couwords(line)
print "This file has %s word(s)." %tot
inp.close()
$ 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):
   if(k==0)or(k==1):
     return 1
   else:
     return k*facto(k-1)

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



Back to Electronics Page

Back to Hiro's Physics Main