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

Built-in functions in Python

The function, len(), gives the highest number of elements in the list. For example,
b = "I spent money."
print len(b)
$ 14
You can put a string directly into the function.

To sort the elements of a list, you will use sort command:
print c
$ [0, 1, 2, 3, 4]
To reverse the elements, use c.reverse().

The following is not exactly a built-in function, but this arrangement makes sure if there is the specified element in the array. The output is either "True" or "False."
print 5 in c
print 3 in c
$ False
$ True
The arguments, 5 and 3, are possible elements in the list, c.

You can also specify a letter or sequence of letters by using find method:
val = "01234567"
print val.find("23")
print val.find("6")
$ 2
$ 6

The set() command excludes the repeated elements from the list.
print aa4
$ set(['a', 'c', 'b', 'd'])
The set() enables the data set to be manipulated by logical operations. -, |, &, and ^ are difference, union, intersection, and symmetric difference, respectively. Define another set:
print aa4-bb4, aa4|bb4, aa4&bb4, aa4^bb4
$ set(['c', 'd']) set(['a', 'c', 'b', 'd', 'f']) set(['a', 'b']) set(['c', 'd', 'f'])

The range() method creates a sequence of numbers.
print cc1
$ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The range() takes 3 arguments; for example, you can make range(1,7,2). This gives a sequence of numbers from 1 through 7 by increment 2.

The method, split(), makes a string data list out of a sequence of letters. For example,
print aas
$ ['2012', '10', '12']
The method, join(), is an opposite command to split():
print alle
$ a-b-c

The tuple and list can be converted mutually by using methods, list() and tuple().

print bb3, cc3
$ [1, 2, 3] (1, 2, 3)

The map function is to operate on each element of a list or a tuple. For example,
import math
print map(math.sin,[0,1,2])
print bb3, cc3
Import calls a math module here. The above gives values of sine of each element.
$ [0.0, 0.8414709848078965, 0.9092974268256817]

Let's use the following dictionary data:
The methods, keys(), values(), and items() extract each into another list.
$ ['p2', 'p3', 'p1']
$ [100, 35, 20]
$ [('p2', 100), ('p3', 35), ('p1', 20)]

Back to Electronics Page

Back to Hiro's Physics Main