现在我们来看下我们的第一次编码。众所周知,python是一门解释性语言,你可以在python解释器中直接写代码,也可以将之写到文件中,然后执行这个文件。首先,我们将用python的解释器来作示范,启动python:在终端或shell下键入“python":
[kd@kdlappy ~]$ python
Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
作为第一次编码,我们将打印经典的"Hello World!",如下所示:
>>> print "Hello World!"
Hello World!
作为正式的程序员,你可能要将上述代码写到一个文件。那么我们来建立一个文件名为helloworld.py的文件,用你喜欢的任何编辑器,我用的是vi,你可以使用基于GUI的工具,如kate,gedit等。
#!/usr/bin/env python
print "Hello World!"
欲运行上述写下的代码,你首先得使文件属性为可执行,在GNU/Linux环境下,你可以在shell中执行如下命令:
$ chmod +x helloworld.py
这时你可以执行此文件了。
$ ./helloworld.py
Hello World!
在代码的第一行我们以#! 开始,我们称之为sha-bang。这样做的目的是告诉shell用python解释器来执行下面代码。接下来的一行,仅仅是打印一条信息。在python中我们认为所有的文本行都是strings类型(下面会讲到python数据类型--译者注)。
在python语言中,空格很重要。我们使用空格将标志符区分开。空格在行的开始处被称之为缩排,但是如果你写了错误的缩排,python解释器将抛出错误。例如下面情形:
>>> a = 12
>>> a = 12
File "<stdin>", line 1
a = 12
^
IndentationError: unexpected indent
警告
在第二行的开始处出现了多余的空格,以至于引起错误。所以要经常检查合适的缩排!
如果你混合使用制表符和空格,这种缩排错误会常见。所以建议如果使用空格,就一直用空格作缩排,不要使用制表符。对于你来说他们俩是一样的,但是你试图去运行的时候,代码会给你抛出错误
注释是一些英语文本方式提供解释此处代码是做什么的,我们写在代码中写注释是便于其他人容易理解。python的注释是以#开始的行,注释在程序中将被忽略,也就是说对程序没有任何的作用。
>>> #this is a comment
>>> #the next line will add two numbers
>>> a = 12 + 34
>>> print c #this is a comment too :)
模块是包含可以直接使用(重用)的函数定义、变量的python文件,它们通常是以.py为扩展名。Python本身在安装时就带有大量的模块。我们将会用到一部分。欲使用模块你首先的将之导入(import)。
>>> import math
>>> print math.e
2.71828182846
我们将会在Modules那章中学习更多的关于模块的内容。
在Python代码中你将用到大量的表达式。表达式由操作符和操作数组成。像2 + 3就是一个表达式。
运算符只是一种告诉python解释器去做一些数学或逻辑操作的符号。一些基本的数学操作符如下所示:
>>> 2 + 3
5
>>> 23 - 3
20
>>> 22.0 / 12
1.8333333333333333
想要得到浮点数的结果,你必须用浮点数作操作数来实现除法运算。求余的符号是 %
>>> 14 % 3
2
代码
#!/usr/bin/env python
days = int(raw_input("Enter days: "))
months = days / 30
days = days % 30
print "Months = %d Days = %d" % (months, days)
输出
[kd@kdlappy book]$ ./integer.py
Enter days: 265
Months = 8 Days = 25
在头一行中我获得用户输入的天数,然后得到月份数和具体的天数并打印出来。你可以使用更容易的方法
#!/usr/bin/env python
days = int(raw_input("Enter days: "))
print "Months = %d Days = %d" % (divmod(days, 30))
divmod(num1, num2)函数返回两个值,第一个是num1和num2相除得到的值,第二个是num1和num2求余得到的值。
你可以使用下面的操作符来实现关系运算
关系操作符
数学运算符 | 含义 |
---|
< | 小于 |
<= | 小于等于 |
> | 大于 |
>= | 大于等于 |
== | 等于 |
!= | 不等于 |
一些实例
>>> 1 < 2
True
>>> 3 > 34
False
>>> 23 == 45
False
>>> 34 != 323
True
// 操作符会给出平除运算结果
>>> 4.0 // 3
1.0
>>> 4.0 / 3
1.3333333333333333
作逻辑运算的“与”,“或”,我们用 and , or关键字。 如果x 是False x and y 返回False否则返回y的值。如果x 是Ture,它返回真。
>>> 1 and 4
4
>>> 1 or 4
1
>>> -1 or 4
-1
>>> 0 or 4
4
x op = expression 为简写运算的语法形式。它将计算形如x = x op expression ,例如
>>> a = 12
>>> a += 13
>>> a
25
>>> a /= 3
>>> a
8
>>> a += (26* 32)
>>> a
840
shorthand.py 实例
#!/usr/bin/env python
N = 100
a = 2
while a < N:
print "%d" % a
a *= a
输出
[kd@kdlappy book]$ ./shorthand.py
2
4
16
我们一般写表达式的时候,在远算符的前后都加一个空格,这样使代码更可读。如
a = 234 * (45 - 56.0 / 34)
一个用于演示表达式的例子
#!/usr/bin/env python
a = 9
b = 12
c = 3
x = a -b / 3 + c * 2 -1
y = a -b / (3 + c) * (2 -1)
z = a - (b / (3 +c) * 2) -1
print "X = ", x
print "Y = ", y
print "Z = ", z
输出
[kd@kdlappy book]$ ./evaluationexp.py
X = 10
Y = 7
Z = 4
x作为第一个被计算。步骤如下所示
9 - 12 / 3 + 3 * 2 -1
9 - 4 + 3 * 2 - 1
9 - 4 + 6 - 1
5 + 6 -1
11 - 1
10
现在y 和 z均有括号,所以表达式计算会有不同的方式。请读者自行检验。
我们可以手动的去作类型转换,如
float(string) -> float value
int(string) -> integer value
str(integer) or str(float) -> string representation
>>> a = 8.126768
>>> str(a)
'8.126768'
这个程序计算1/x+1/(x+1)+1/(x+2)+ ... +1/n 直到n.在此例中x = 1 , n =10
#!/usr/bin/env python
sum = 0.0
for i in range(1, 11):
sum += 1.0 / i
print "%2d %6.4f" % (i , sum)
输出
[kd@kdlappy book]$ ./evaluateequ.py
1 1.0000
2 1.5000
3 1.8333
4 2.0833
5 2.2833
6 2.4500
7 2.5929
8 2.7179
9 2.8290
10 2.9290
sum += 1.0 / i 是和sum = sum + 1.0 / i表达的相同的意思。
4.9. quadraticequation.py
这是一个模拟二次方运算的程序
#!/usr/bin/env python
import math
a = int(raw_input("Enter value of a: "))
b = int(raw_input("Enter value of b: "))
c = int(raw_input("Enter value of c: "))
d = b * b - 4 * a * c
if d < 0:
print "ROOTS are imaginary"
else:
root1 = (-b + math.sqrt(d)) / (2.0 * a)
root2 = (-b - math.sqrt(d)) / (2.0 * a)
print "Root 1 = ", root1
print "Root 2 = ", root2
在这个例子中我们将计算一位数码相机的销售人员的工资。他的基本工资是1500,每售出一台数码相机他可以得到200而且他的月任务是%2.输入表示的分别是售出的数码相机的台数和总的数码相机的价格。
#!/usr/bin/env python
basic_salary = 1500
bonus_rate = 200
commision_rate = 0.02
numberofcamera = int(raw_input("Enter the number of inputs sold: "))
price = float(raw_input("Enter the total prices: "))
bonus = (bonus_rate * numberofcamera)
commision = (commision_rate * numberofcamera * price)
print "Bonus = %6.2f" % bonus
print "Commision = %6.2f" % commision
print "Gross salary = %6.2f" % ( basic_salary + bonus + commision)
输出
[kd@kdlappy book]$ ./salesmansalary.py
Enter the number of inputs sold: 5
Enter the total prices: 20450
Bonus = 1000.00
Commision = 2045.00
Gross salary = 4545.00
In the examples we used before , sometimes it was required to do the same work couple of times. We use a counter to check how many times the code needs to be executed. This technique is known as looping. First we are going to look into while statement for looping.
The syntax for while statement is like
while condition:
statement1
statement2
The code we want to reuse must be indented properly under the while statement. They will be executed if the condition is true. Again like in if-else statement any non zero value is true. Let us write a simple code to print numbers 0 to 10
>>> n = 0
>>> while n < 11:
... print n
... n += 1
...
0
1
2
3
4
5
6
7
8
9
10
In the first line we are setting n = 0, then in the while statement the condition is n < 11 , that means what ever line indented below that will execute until n becomes same or greater than 11. Inside the loop we are just printing the value of n and then increasing it by one.
Let us try to solve Fibonacci series. In this series we get the next number by adding the previous two numbers. So the series looks like 1,1,2,3,5,8,13 .......
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
print b
a, b = b, a + b
The output
[kd@kdlappy book]$ ./fibonacci1.py
1
1
2
3
5
8
13
21
34
55
89
In the first line of the code we are initializing a and b, then looping while b's value is less than 100. Inside the loop first we are printing the value of b and then in the next line putting the value of b to a and a + b to b in the same line.
If you put a trailing comma in the print statement , then it will print in the same line
#!/usr/bin/env python
a, b = 0, 1
while b < 100:
print b,
a, b = b, a + b
The output
[kd@kdlappy book]$ ./fibonacci2.py
1 1 2 3 5 8 13 21 34 55 89
Let us write a program to evaluate the power series. The series looks like e**x =1+x+x**2/2! +x**3/3! +....+ x**n/n! where 0 <x <1
#!/usr/bin/env python
x = float(raw_input("Enter the value of x: "))
n = term = num = 1
sum = 1.0
while n <= 100:
term *= x / n
sum += terrm
n += 1
if term < 0.0001:
break
print "No of Times= %d and Sum= %f" % (n, sum)
The output
kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0
No of Times= 2 and Sum= 1.000000
[kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0.1
No of Times= 5 and Sum= 1.105171
[kd@kdlappy book]$ ./powerseries.py
Enter the value of x: 0.5
No of Times= 7 and Sum= 1.648720
In this program we introduced a new keyword called break. What break does is stop the innermost loop. In this example we are using break under the if statement
if term < 0.0001:
break
This means if the value of term is less than 0.0001 then get out of the loop.
6.4. Multiplication Table
In this example we are going to print the multiplication table up to 10.
#!/usr/bin/env python
i = 1
print "-" * 50
while i < 11:
n = 1
while n <= 10:
print "%4d" % (i * n),
n += 1
print ""
i += 1
print "-" * 50
The output
[kd@kdlappy book]$ ./multiplication.py
--------------------------------------------------
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
--------------------------------------------------
Here we used one while loop inside another loop, this is known as nested looping. You can also see one interesting statement here
print "-" * 50
In a print statement if we multiply the string with an integer n , the string will be printed nmany times. Some examples
>>> print "*" * 10
**********
>>> print "#" * 20
####################
>>> print "--" * 20
----------------------------------------
>>> print "-" * 40
----------------------------------------
6.5. Some printing * examples
Here are some examples which you can find very often in college lab reports
Design 1
#!/usr/bin/env python
row = int(raw_input("Enter the number of rows: "))
n = row
while n >= 0:
x = "*" * n
print x
n -= 1
The output
[kd@kdlappy book]$ ./design1.py
Enter the number of rows: 5
*****
****
***
**
*
Design 2
#!/usr/bin/env python
n = int(raw_input("Enter the number of rows: "))
i = 1
while i <= n:
print "*" * i
i += 1
The output
[kd@kdlappy book]$ ./design2.py
Enter the number of rows: 5
*
**
***
****
*****
Design 3
#!/usr/bin/env python
row = int(raw_input("Enter the number of rows: "))
n = row
while n >= 0:
x = "*" * n
y = " " * (row - n)
print y + x
n -= 1
The output
[kd@kdlappy book]$ ./design3.py
Enter the number of rows: 5
*****
****
***
**
*
We are going to learn a data structure called list before we go ahead to learn more on looping. Lists an be written as a list of comma-separated values (items) between square brackets.
>>> a = [ 1 , 342, 2233423, 'India', 'Fedora']
>>> a
[1, 342, 2233423, 'India', 'Fedora']
Lists can keep any other data inside it. It works as a sequence too, that means
>>> a[0]
1
>>> a[4]
'Fedora'
You can even slice it into different pieces, examples are given below
>>> a[4]
'Fedora'
>>> a[-1]
'Fedora'
>>> a[-2]
'India'
>>> a[0:-1]
[1, 342, 2233423, 'India']
>>> a[2:-2]
[2233423]
>>> a[:-2]
[1, 342, 2233423]
>>> a[0::2]
[1, 2233423, 'Fedora']
In the last example we used two :(s) , the last value inside the third brackets indicates step. s[i:j:k] means slice of s from i to j with step k.
To check if any value exists within the list or not you can do
>>> a = ['Fedora', 'is', 'cool']
>>> 'cool' in a
True
>>> 'Linux' in a
False
That means we can use the above statement as if clause expression. The built-in function len() can tell the length of a list.
>>> len(a)
3
There is another to loop by using for statement. In python the for statement is different from the way it works in C. Here for statement iterates over the items of any sequence (a list or a string). Example given below
>>> a = ['Fedora', 'is', 'powerfull']
>>> for x in a:
... print x,
...
Fedora is powerfull
We can also do things like
>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> for x in a[::2]:
... print x
...
1
3
5
7
9
range() is a buitin function. From the help document
range(...)
range([start,] stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
Now if you want to see this help message on your system type help(range) in the python interpreter. help(s) will return help message on the object s. Examples of range function
>>> range(1,5)
[1, 2, 3, 4]
>>> range(1,15,3)
[1, 4, 7, 10, 13]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Just like break we have another statement, continue, which skips the execution of the code after itself and goes back to the start of the loop. That means it will help you to skip a part of the loop. In the below example we will ask the user to input an integer, if the input is negative then we will ask again, if positive then we will square the number. To get out of the infinite loop user must input 0.
#!/usr/bin/env python
while True:
n = int(raw_input("Please enter an Integer: "))
if n < 0:
continue #this will take the execution back to the starting of the loop
elif n == 0:
break
print "Square is ", n ** 2
print "Goodbye"
The output
[kd@kdlappy book]$ ./continue.py
Please enter an Integer: 34
Square is 1156
Please enter an Integer: 4
Square is 16
Please enter an Integer: -9
Please enter an Integer: 0
Goodbye
We can have an optional else statement after any loop. It will be executed after the loop unless a break statement stopped the loop.
>>> for i in range(0,5):
... print i
... else:
... print "Bye bye"
...
0
1
2
3
4
Bye bye
We will see more example of break and continue later in the book.
Python有许多内建的数据结构。如果你还想知道什么是数据结构,其实她除了存储数据和一些特殊的操作技巧之外什么也不是。我们在以前已经见过列表了,现在我们来深入的了解一下。
>>> a = [23, 45, 1, -3434, 43624356, 234]
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45]
首先我们建立了一个列表 a. 然后添加元素 45 到列表的末尾,我们调用函数 a.append(45)。 你可以看到元素 45 已经添加到列表的末端了。 有时候我们需要将数据插入到列表的任何位置,这时我们使用函数insert()。
>>> a.insert(0, 1) # 1 added at the 0th position of the list
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45]
>>> a.insert(0, 111)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 234, 45]
count(s)将返回出现在列表中 s 的次数。这里我们将检验在此列表中出现45 的次数。
>>> a.count(45)
2
如果你想从列表中去掉一些元素,那么请使用函数remove()。
>>> a.remove(234)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45]
将整个列表反转后输出
>>> a.reverse()
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111]
我们可以在列表里存储任何数据,现在我们来将一个列表b 添加到列表a 中,呵呵,你看到了吧!我们接着学习如何将b 中的值添加到a 中。
>>> b = [45, 56, 90]
>>> a.append(b)
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90]]
>>> a[-1]
[45, 56, 90]
>>> a.extend(b) #To add the values of b not the b itself
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90], 45, 56, 90]
>>> a[-1]
90
如上,你可以看到我们用a.extend()方法来扩展列表的了。要是为列表排序,我们使用sort()方法。
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356, [45, 56, 90]]
你也可以用关键字del来删除列表中的任何元素。
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356]
栈是我们通常所说的一种LIFO(Last In First Out)数据结构。它的意思是数据在最后的位置上进入,并且最后进入的数据第一个出来。最简单的例子洗一打盘子,如果你想让最下边的那个盘子,你必须将上面的一一拿走,最先拿走的就是最上面的那个盘子。代码同样可以达到目标
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.pop()
6
>>> a.pop()
5
>>> a.pop()
4
>>> a.pop()
3
>>> a
[1, 2]
>>> a.append(34)
>>> a
[1, 2, 34)
我们刚学到一新的方法,如上pop().pop(i)方法,可以从列表中将第i个元素踢出来。
在我们每天的生活中都可以遇到队列多次,比如售票窗口、图书馆、超市的结帐出口。队列是一种你可以在后面追加数据但只能从开始拿出数据的数据结构,这就是为什么它是FIFO(First In First Out).
>>> a = [1, 2, 3, 4, 5]
>>> a.append(1)
>>> a
[1, 2, 3, 4, 5, 1]
>>> a.pop(0)
1
>>> a.pop(0)
2
>>> a
[3, 4, 5, 1]
欲从列表中踢出第一个元素,我们用方法a.pop(0)
List comprehensions provide a concise way to create lists. Each list comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it.
For example if we want to make a list out of the square values of another list, then
>>> a = [1, 2, 3]
>>> [x ** 2 for x in a]
[1, 4, 9]
>>> z = [x + 1 for x in [x ** 2 for x in a]]
>>> z
[2, 5, 10]
Above in the second case we used two list comprehensions in a same line.
Tuples are data separated by comma.
>>> a = 'Fedora', 'Debian', 'Kubuntu', 'Pardus'
>>> a
('Fedora', 'Debian', 'Kubuntu', 'Pardus')
>>> a[1]
'Debian'
>>> for x in a:
... print x,
...
Fedora Debian Kubuntu Pardus
You can also unpack values of any tuple in to variables, like
>>> divmod(15,2)
(7, 1)
>>> x, y = divmod(15,2)
>>> x
7
>>> y
1
Tuples are immutable, that means you can not del/add/edit any value inside the tuple. Here is another example
>>> a = (1, 2, 3, 4)
>>> del a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion
Above you can see python is giving error when we are trying to delete a value in the tuple.
To create a tuple which contains only one value you have to type a trailing comma.
>>> a = (123)
>>> a
123
>>> type(a)
<type 'int'>
>>> a = (123, ) #Look at the trailing comma
>>> a
(123,)
>>> type(a)
<type 'tuple'>
Using the buitin function type() you can know the data type of any variable. Remember the len() function we used to find the length of any sequence ?
>>> type(len)
<type 'bulletin_function_or_method'>
Sets are another type of data structure with no duplicate items. We can also mathematical set operations on sets.
>>> a = set('abcthabcjwethddda')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 't', 'w'])
And some examples of the set operations
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b # letters in both a and b
set(['a', 'c'])
>>> a ^ b # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l'])
To add or pop values from a set
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 't', 'w'])
>>> a.add('p')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 'p', 't', 'w'])
Dictionaries are unordered set of key: value pairs where keys are unique. We declare dictionaries using {} braces. We use dictionaries to store data for any particular key and then retrieve them.
>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_']
'Debian'
We can add more data to it by simply
>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
To delete any particular key:value pair
>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'
To check if any key is there in the dictionary or not you can use has_key() or in keyword.
>>> data.has_key('Soumya')
False
>>> 'Soumya' in data
False
You must remember that no mutable object can be a key, that means you can not use a list as a key.
dict() can create dictionaries from tuples of key,value pair.
>>> dict((('Indian','Delhi'),('Bangladesh','Dhaka')))
{'Indian': 'Delhi', 'Bangladesh': 'Dhaka'}
If you want to loop through a dict use iteritems() method.
>>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.iteritems():
... print "%s uses %s" % (x, y)
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu
If you want to loop through a list (or any sequence) and get iteration number at the same time you have to use enumerate().
>>> for i, j in enumerate(['a', 'b', 'c']):
... print i, j
...
0 a
1 b
2 c
You may also need to iterate through two sequences same time, for that use zip() function.
>>> a = ['Pradeepto', 'Kushal']
>>> b = ['OpenSUSE', 'Fedora']
>>> for x, y in zip(a, b):
... print "%s uses %s" % (x, y)
...
Pradeepto uses OpenSUSE
Kushal uses Fedora
In this example , you have to take number of students as input , then ask marks for three subjects as 'Physics', 'Maths', 'History', if the total number for any student is less 120 then print he failed, or else say passed.
#!/usr/bin/env python
n = int(raw_input("Enter the number of students:"))
data = {} # here we will store the data
languages = ('Physics', 'Maths', 'History') #all languages
for i in range(0, n): #for the n number of students
name = raw_input('Enter the name of the student %d: ' % (i + 1)) #Get the name of the student
marks = []
for x in languages:
marks.append(int(raw_input('Enter marks of %s: ' % x))) #Get the marks for languages
data[name] = marks
for x, y in data.iteritems():
total = sum(y)
print "%s 's total marks %d" % (x, total)
if total < 120:
print "%s failed :(" % x
else:
print "%s passed :)" % y
The output
[kd@kdlappy book]$ ./students.py
Enter the number of students:2
Enter the name of the student 1: Babai
Enter marks of Physics: 12
Enter marks of Maths: 45
Enter marks of History: 40
Enter the name of the student 2: Ria
Enter marks of Physics: 89
Enter marks of Maths: 98
Enter marks of History: 40
Babai 's total marks 97
Babai failed :(
Ria 's total marks 227
Ria passed :)
In this example we will multiply two matrix's. First we will take input the number of rows/columns in the matrix (here we assume we are using n x n matrix). Then values of the matrix's.
#!/usr/bin/env python
n = int(raw_input("Enter the value of n: "))
print "Enter values for the Matrix A"
a = []
for i in range(0, n):
a.append([int(x) for x in raw_input("").split(" ")])
print "Enter values for the Matrix B"
b = []
for i in range(0, n):
b.append([int(x) for x in raw_input("").split(" ")])
c = []
for i in range(0, n):
c.append([a[i][j] * b[j][i] for j in range(0,n)])
print "After matrix multiplication"
print "-" * 10 * n
for x in c:
for y in x:
print "%5d" % y,
print ""
print "-" * 10 * n
The output
[kd@kdlappy book]$ ./matrixmul.py
Enter the value of n: 3
Enter values for the Matrix A
1 2 3
4 5 6
7 8 9
Enter values for the Matrix B
9 8 7
6 5 4
3 2 1
After matrix multiplication
------------------------------
9 12 9
32 25 12
49 32 9
------------------------------
Here we have used list comprehensions couple of times. [int(x) for x in raw_input("").split(" ")] here first it takes the input as string by raw_input(), then split the result by " ", then for each value create one int. We are also using [a[i][j] * b[j][i] for j in range(0,n)] to get the resultant row in a single line.
Strings are nothing but simple text. In python we declare strings in between "" or '' or ''' ''' or """ """. The examples below will help you to understand sting in a better way.
>
>
> s = "I am Indian"
>
>
> s
'I am Indian'
>
>
> s = 'I am Indian'
>
>
> s = "Here is a line \
... splitted in two lines"
>
>
> s
'Here is a line splitted in two lines'
>
>
> s = "Here is a line \n splitted in two lines"
>
>
> s
'Here is a line \n splitted in two lines'
>
>
> print s
Here is a line
splitted in two lines
Now if you want to multiline strings you have to use triple single/double quotes.
>
>
> s = """ This is a
... multiline string, so you can
... write many lines"""
>
>
> print s
This is a
multiline string, so you can
write many lines
8.1. Different methods available for Strings
Every string object is having couple of buildin methods available, we already saw some of them like s.split(" ").
>
>
> s = "kushal das"
>
>
> s.title()
'Kushal Das'
title() method returns a titlecased version of the string, words start with uppercase characters, all remaining cased characters are lowercase.
>
>
> z = s.upper()
>
>
> z
'KUSHAL DAS'
>
>
> z.lower()
'kushal das'
upper() returns a total uppercase version whereas lower() returns a lower case version of the string.
>
>
> s = "I am A pRoGraMMer"
>
> s.swapcase()
'i AM a PrOgRAmmER'
swapcase() returns the string with case swapped :)
>
>
> s = "jdwb 2323bjb"
>
>
> s.isalnum()
False
>
>
> s = "jdwb2323bjb"
>
>
> s.isalnum()
True
Because of the space in the first line isalnum() returned False , it checks for all charecters are alpha numeric or not.
>
>
> s = "SankarshanSir"
>
>
> s.isalpha()
True
>
>
> s = "Sankarshan Sir"
>
>
> s.isalpha()
False
isalpha() checkes for only alphabets.
>
>
> s = "1234"
>
>
> s.isdigit() #To check if all the characters are digits or not
True
>
>
> s = "Fedora9 is coming"
>
>
> s.islower() # To check if all chracters are lower case or not
False
>
>
> s = "Fedora9 Is Coming"
>
>
> s.istitle() # To check if it is a title or not
True
>
>
> s = "INDIA"
>
>
> s.isupper() # To check if characters are in upper case or not
True
To split any string we have split(). It takes a string as an argument , depending on that it will split the main string and returns a list containing splitted strings.
>
>
> s = "We all love Python"
>
>
> s.split(" ")
['We', 'all', 'love', 'Python']
>
>
> x = "Nishant:is:waiting"
>
>
> x.split(':')
['Nishant', 'is', 'waiting']
The opposite method for split() is join(). It takes a list contains strings as input and join them.
>
>
> "-".join("GNU/Linux is great".split(" "))
'GNU/Linux-is-great'
In the above example first we are splitting the string "GNU/Linux is great" based on the white space, then joining them with "-".
Strings do have few methods to do striping. The simplest one is strip(chars). If you provide the chars argument then it will strip any combination of them. By default it strips only whitespace or newline characters.
>
>
> s = " abc\n "
>
>
> s.strip()
'abc'
You can particularly strip from the left hand or right hand side also using lstrip(chars) or rstrip(chars).
>
>
> s = "www.foss.in"
>
>
> s.lstrip("cwsd.")
'foss.in'
>
>
> s.rstrip("cnwdi.")
'www.foss'
Stings have some methods which will help you in finding text/substring in a string. Examples are given below:
>
>
> s.find("for")
7
>
>
> s.find("fora")
-1
>
>
> s.startswith("fa") #To check if the string startswith fa or not
True
>
>
> s.endswith("reason") #
True
find() helps to find the first occurrence of the substring given, if not found it returns -1.
Palindrome are the kind of strings which are same from left or right whichever way you read them. Example "madam". In this example we will take the word as input from the user and say if it is palindrome or not.
#!/usr/bin/env python
s = raw_input("Please enter a string: ")
z = [x for x in s]
z.reverse()
if s == "".join(z):
print "The string is a palindrome"
else:
print "The string is not a palindrome"
The output
[kd@kdlappy book]$ ./palindrome.py
Please enter a string: madam1
The string is not a palindrome
[kd@kdlappy book]$ ./palindrome.py
Please enter a string: madam
The string is a palindrome
In this example we will count the number of words in a given line
#!/usr/bin/env python
s = raw_input("Enter a line: ")
print "The number of words in the line are %d" % (len(s.split(" ")))
The output
[kd@kdlappy book]$ ./countwords.py
Enter a line: Sayamindu is a great programmer
The number of words in the line are 5
Reusing the same code is required many times within a same program. Functions help us to do so. We write the things we have to do repeatedly in a function then call it where ever required. We already saw build in functions like len(), divmod().
We use def keyword to define a function. general syntax is like
def functionname(params):
statement1
statement2
Let us write a function which will take two integers as input and then return the sum.
>
>
> def sum(a, b):
... return a + b
In the second line with the return keyword, we are sending back the value of a + b to the caller. You must call it like
>
>
> res = sum(234234, 34453546464)
>
>
> res
34453780698L
Remember the palindrome program we wrote in the last chapter. Let us write a function which will check if a given string is palindrome or not, then return True or False.
#!/usr/bin/env python
def palindrome(s):
z = s
z = [x for x in z]
z.reverse()
if s == "".join(z):
return True
else:
return False
s = raw_input("Enter a string: ")
if palindrome(s):
print "Yay a palindrome"
else:
print "Oh no, not a palindrome"
Now run the code :)
9.2. Local and global variables
To understand local and global variables we will go through two examples.
#!/usr/bin/env python
def change(b):
a = 90
print a
a = 9
print "Before the function call ", a
print "inside change function",
change(a)
print "After the function call ", a
The output
[kd@kdlappy book]$ ./local.py
Before the function call 9
inside change function 90
After the function call 9
First we are assigning 9 to a, then calling change function, inside of that we are assigning 90 to a and printing a. After the function call we are again printing the value of a. When we are writing a = 90 inside the function, it is actually creating a new variable called a, which is only available inside the function and will be destroyed after the function finished. So though the name is same for the variable a but they are different in and out side of the function.
#!/usr/bin/env python
def chvariable ange(b):
global a
a = 90
print a
a = 9
print "Before the function call ", a
print "inside change function",
change(a)
print "After the function call ", a
Here by using global keyword we are telling that a is globally defined, so when we are changing a's value inside the function it is actually changing for the a outside of the function also.
9.3. Default argument value
In a function variables may have default argument values, that means if we don't give any value for that particular variable it will assigned automatically.
>
>
> def test(a , b = -99):
... if a
> b:
... return True
... else:
... return False
In the above example we have written b = -99 in the function parameter list. That means of no value for b is given then b's value is -99. This is a very simple example of default arguments. You can test the code by
>
>
> test(12, 23)
False
>
>
> test(12)
True
Important
Remember that you can not have an argument without default argument if you already have one argument with default values before it. Like f(a, b=90, c) is illegal as b is having a default value but after that c is not having any default value.
Also remember that default value is evaluated only once, so if you have any mutable object like list it will make a difference. See the next example
>
>
> def f(a, data=[]):
... data.append(a)
... return data
...
>
>
> print f(1)
[1]
>
>
> print f(2)
[1, 2]
>
>
> print f(3)
[1, 2, 3]
>
>
> def func(a, b=5, c=10):
... print 'a is', a, 'and b is', b, 'and c is', c
...
>
>
> func(12, 24)
a is 12 and b is 24 and c is 10
>
>
> func(12, c = 24)
a is 12 and b is 5 and c is 24
>
>
> func(b=12, c = 24, a = -1)
a is -1 and b is 12 and c is 24
In the above example you can see we are calling the function with variable names, like func(12, c = 24), by that we are assigning 24 to c and b is getting its default value. Also remember that you can not have without keyword based argument after a keyword based argument. like
>
>
> def func(a, b=13, v):
... print a, b, v
...
File "<stdin
>", line 1
SyntaxError: non-default argument follows default argument
A file is some information or data which stays in the computer storage devices. You already know about different kinds of file , like your music files, video files, text files. Python gives you easy ways to manipulate these files. Generally we divide files in two categories, text file and binary file. Text files are simple text where as the binary files contain binary data which is only readable by computer.
To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open. Modes are like
"r" -> open read only, you can read the file but can not edit / delete anything inside |
"w" -> open with write power, means if the file exists then delete all content and open it to write |
"a" -> open in append mode |
The default mode is read only, ie if you do not provide any mode it will open the file as read only. Let us open a file
>
>
> f = open("love.txt")
>
>
> f
<open file 'love.txt', mode 'r' at 0xb7f2d968>
To read the whole file at once use the read() method.
>
>
> f = open("sample.txt")
>
>
> f.read()
'I love Python\nPradeepto loves KDE\nSankarshan loves Openoffice\n'
If you call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file.
>
>
> f = open("sample.txt")
>
>
> f.readline()
'I love Python\n'
>
>
> f.readline()
'Pradeepto loves KDE\n'
To read all the all the lines in a list we use readlines() method.
>
>
> f = open("sample.txt")
>
>
> f.readlines()
['I love Python\n', 'Pradeepto loves KDE\n', 'Sankarshan loves Openoffice\n']
You can even loop through the lines in a file object.
>
>
> f = open("sample.txt")
>
>
> for x in f:
... print x,
...
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice
Let us write a program which will take the file name as the input from the user and show the content of the file in the console.
#!/usr/bin/env python
name = raw_input("Enter the file name: ")
f = open(name)
print f.read()
f.close()
In the last line you can see that we closed the file object with the help of close() method.
The output
[kd@kdlappy book]$ ./showfile.py
Enter the filename: sample.txt
I love Python
Pradeepto loves KDE
Sankarshan loves Openoffice
Let us open a file then we will write some random text into it by using the write() method.
>
>
> f = open("ircnicks.txt", 'w')
>
>
> f.write('powerpork\n')
>
>
> f.write('indrag\n')
>
>
> f.write('mishti\n')
>
>
> f.write('sm|CPU')
>
>
> f.close()
Now read the file we just created
>
>
> f = open('ircnicks.txt')
>
>
> s = f.read()
>
>
> print s
powerpork
indrag
mishti
sm|CPU
In this example we will copy a given file to another file.
#!/usr/bin/env python
import sys
if len(sys.argv) < 3:
print "Wrong parameter"
print "./copyfile.py file1 file2"
sys.exit(1)
f1 = open(sys.argv[1])
s = f1.read()
f1.close()
f2 = open(sys.argv[2], 'w')
f2.write(s)
f2.close()
You can see we used a new module here sys. sys.argv contains all command line parameters. Remember cp command in shell, after cp we type first the file to be copied and then the new file name.
The first value in sys.argv is the name of the command itself.
#!/usr/bin/env python
import sys
print "First value", sys.argv[0]
print "All values"
for i, x in enumerate(sys.argv):
print i, x
The output
[kd@kdlappy book]$ ./argvtest.py Hi there
First value ./argvtest.py
All values
0 ./argvtest.py
1 Hi
2 there
Here we used a new function enumerate(iterableobject), which returns the index number and the value from the iterable object.
10.5. Random seeking in a file
You can also randomly move around inside a file using seek() method. It takes two arguments , offset and whence. To know more about it let us read what python help tells us
seek(...) seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are speakable.
Let us see one example
>
>
> f = open('tempfile', 'w')
>
>
> f.write('0123456789abcdef')
>
>
> f.close()
>
>
> f = open('tempfile')
>
>
> f.tell() #tell us the offset position
0L
>
>
> f.seek(5) # Goto 5th byte
>
>
> f.tell()
5L
>
>
> f.read(1) #Read 1 byte
'5'
>
>
> f.seek(-3, 2) # goto 3rd byte from the end
>
>
> f.read() #Read till the end of the file
'def'