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

Data expressions

There is a tuple consisting of a number of values separated by commas. The set of the values are bundled by parentheses. Each element can be displayed, but it cannot be replaced by another value. The following is an example of tuple:
There is another type that is called list. An element of a list can be replaced by another value. That is bundled by square brakets.
Each element of a list is independent. Let us perform following:
print a,b,a+b,a[1]
The output is:
$ [4, 't', 0.083] [7, 'u', 260.0] [4, 't', 0.083, 7, 'u', 260.0] t
There is also a convenient expression. Suppose you have a string:
s = "abcdefghi"
The numbers and collon specify the sequence of the data.
print s[0:4]
The result is:
$ abcd
The other cases are:
print s[:4]
print s[1]
print s[1:-1]
print s[1:]
print s[1:4]
Each output is:
$ abcd
$ b
$ bcdefgh
$ bcdefghi
$ bcd

There is a dictionary that can register two elements as an item. Each element is called key and value, respectively. The data set is bundled by curly brakets:
Once you specify one of the keys, the value will be returned automatically. Note that you have to use square brakets for this command:
print aa5["quality"]
$ 350
A value of the key can be replaced as follows:
print aa5
$ {'price': 300, 'quality': 150, 'value': 200}

Let's prepare for 3 types of data:
The print command has format options. %d, %f, %s and %x format integer, float, string, and hexadecimal respectively. For example,
print "I weigh %f kilograms." %aa6
print "My name is %s." %bb6
print "%s has %d dollars." %(bb6,aa6)
The above returns:
$ I weigh 80.500000 kilograms.
$ My name is Hiro.
$ Hiro has 80 dollars.
You can also extract a value from the dictionary data for output:
print "%(physics)f" %cc6
$ 120.000000
To format the number of figures you want to display,
print "I drive at %0.8f miles/h." %(80.0/2.2)
This gives 8 digits after the decimal point as follows:
$ I drive at 36.36363636 miles/h.

Back to Electronics Page

Back to Hiro's Physics Main