python初学程序
###########################################################
可执行的python程序:
vim hello.py
#!/usr/bin/python
# Filename:hello.py
print ‘hello,world‘
chmod a+x hello.py
###########################################################
使用if语句
#!/usr/bin/python
# Filename: if.py
number = 23
guess = int(raw_input(‘Enter an integer : ‘))
if guess == number:
print ‘Congratulations, you guessed it.‘ # New block starts here
print "(but you do not win any prizes!)" # New block ends here
elif guess < number:
print ‘No, it is a little higher than that‘ # Another block
# You can do whatever you want in a block ...
else:
print ‘No, it is a little lower than that‘
# you must have guess > number to reach here
print ‘Done‘
# This last statement is always executed, after the if statement is executed
###########################################################
使用wihle语句:
#!/usr/bin/python
# Filename: while.py
number = 23
running = True
while running:
guess = int(raw_input(‘Enter an integer : ‘))
if guess == number:
print ‘Congratulations, you guessed it.‘
running = False # this causes the while loop to stop
elif guess < number:
print ‘No, it is a little higher than that‘
else:
print ‘No, it is a little lower than that‘
else:
print ‘The while loop is over.‘
# Do anything else you want to do here
print ‘Done‘
###########################################################
使用for语句:
#!/usr/bin/python
# Filename: for.py
for i in range(1, 5):
print i
else:
print ‘The for loop is over‘
###########################################################
使用break
#!/usr/bin/python
# Filename: break.py
while True:
s = raw_input(‘Enter something : ‘)
if s == ‘quit‘:
break
print ‘Length of the string is‘, len(s)
print ‘Done‘
###########################################################
使用continue:
#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input(‘Enter something : ‘)
if s == ‘quit‘:
break
if len(s) < 3:
continue
print ‘Input is of sufficient length‘
# Do other kinds of processing here...
###########################################################
使用函数:
#!/usr/bin/python
# Filename: func_param.py
def printMax(a, b):
if a > b:
print a, ‘is maximum‘
else:
print b, ‘is maximum‘
printMax(3, 4) # directly give literal values
x = 5
y = 7
printMax(x, y) # give variables as arguments
注意:
python中严格格式,注意缩进
###########################################################
局部变量的使用:
#!/usr/bin/python
# Filename: func_local.py
def func(x):
print ‘x is‘, x
x = 2
print ‘Changed local x to‘, x
x = 50
func(x)
print ‘x is still‘, x
###########################################################
使用默认参数值:
#!/usr/bin/python
# Filename: func_default.py
def say(message, times = 1):
print message * times
say(‘Hello‘)
say(‘World‘, 5)
###########################################################
使用关键参数:
#!/usr/bin/python
# Filename: func_key.py
def func(a, b=5, c=10):
print ‘a is‘, a, ‘and b is‘, b, ‘and c is‘, c
func(3, 7)
func(25, c=24)
func(c=50, a=100)
###########################################################
使用return语句
#!/usr/bin/python
# Filename: func_return.py
def maximum(x, y):
if x > y:
return x
else:
return y
print maximum(2, 3)
###########################################################
使用模块
#!/usr/bin/python
# Filename: using_sys.py
import sys
print ‘The command line arguments are:‘
for i in sys.argv:
print i
print ‘\n\nThe PYTHONPATH is‘, sys.path, ‘\n‘
###########################################################
制造自己的模块:
#!/usr/bin/python
# Filename: mymodule.py
def sayhi():
print ‘Hi, this is mymodule speaking.‘
version = ‘0.1‘
# End of mymodule.py
#!/usr/bin/python
# Filename: mymodule_demo.py
import mymodule
mymodule.sayhi()
print ‘Version‘, mymodule.version
###########################################################
使用列表
#!/usr/bin/python
# Filename: using_list.py
# This is my shopping list
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
print ‘I have‘, len(shoplist),‘items to purchase.‘
print ‘These items are:‘, # Notice the comma at end of the line
for item in shoplist:
print item,
print ‘\nI also have to buy rice.‘
shoplist.append(‘rice‘)
print ‘My shopping list is now‘, shoplist
print ‘I will sort my list now‘
shoplist.sort()
print ‘Sorted shopping list is‘, shoplist
print ‘The first item I will buy is‘, shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print ‘I bought the‘, olditem
print ‘My shopping list is now‘, shoplist
###########################################################
使用元组:
#!/usr/bin/python
# Filename: using_tuple.py
zoo = (‘wolf‘, ‘elephant‘, ‘penguin‘)
print ‘Number of animals in the zoo is‘, len(zoo)
new_zoo = (‘monkey‘, ‘dolphin‘, zoo)
print ‘Number of animals in the new zoo is‘, len(new_zoo)
print ‘All animals in new zoo are‘, new_zoo
print ‘Animals brought from old zoo are‘, new_zoo[2]
print ‘Last animal brought from old zoo is‘, new_zoo[2][2]
###########################################################
使用字典:
#!/usr/bin/python
# Filename: using_dict.py
# ‘ab‘ is short for ‘a‘ddress‘b‘ook
ab = { ‘Swaroop‘ : ‘swaroopch@byteofpython.info‘,
‘Larry‘ : ‘larry@wall.org‘,
‘Matsumoto‘ : ‘matz@ruby-lang.org‘,
‘Spammer‘ : ‘spammer@hotmail.com‘
}
print "Swaroop‘s address is %s" % ab[‘Swaroop‘]
# Adding a key/value pair
ab[‘Guido‘] = ‘guido@python.org‘
# Deleting a key/value pair
del ab[‘Spammer‘]
print ‘\nThere are %d contacts in the address-book\n‘ % len(ab)
for name, address in ab.items():
print ‘Contact %s at %s‘ % (name, address)
if ‘Guido‘ in ab: # OR ab.has_key(‘Guido‘)
print "\nGuido‘s address is %s" % ab[‘Guido‘]
###########################################################
使用序列:
#!/usr/bin/python
# Filename: seq.py
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
# Indexing or ‘Subscription‘ operation
print ‘Item 0 is‘, shoplist[0]
print ‘Item 1 is‘, shoplist[1]
print ‘Item 2 is‘, shoplist[2]
print ‘Item 3 is‘, shoplist[3]
print ‘Item -1 is‘, shoplist[-1]
print ‘Item -2 is‘, shoplist[-2]
# Slicing on a list
print ‘Item 1 to 3 is‘, shoplist[1:3]
print ‘Item 2 to end is‘, shoplist[2:]
print ‘Item 1 to -1 is‘, shoplist[1:-1]
print ‘Item start to end is‘, shoplist[:]
# Slicing on a string
name = ‘swaroop‘
print ‘characters 1 to 3 is‘, name[1:3]
print ‘characters 2 to end is‘, name[2:]
print ‘characters 1 to -1 is‘, name[1:-1]
print ‘characters start to end is‘, name[:]
###########################################################
对象与参考
#!/usr/bin/python
# Filename: reference.py
print ‘Simple Assignment‘
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print ‘shoplist is‘, shoplist
print ‘mylist is‘, mylist
# notice that both shoplist and mylist both print the same list without
# the ‘apple‘ confirming that they point to the same object
print ‘Copy by making a full slice‘
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print ‘shoplist is‘, shoplist
print ‘mylist is‘, mylist
# notice that now the two lists are different
###########################################################
字符串的方法:
#!/usr/bin/python
# Filename: str_methods.py
name = ‘Swaroop‘ # This is a string object
if name.startswith(‘Swa‘):
print ‘Yes, the string starts with "Swa"‘
if ‘a‘ in name:
print ‘Yes, it contains the string "a"‘
if name.find(‘war‘) != -1:
print ‘Yes, it contains the string "war"‘
delimiter = ‘_*_‘
mylist = [‘Brazil‘, ‘Russia‘, ‘India‘, ‘China‘]
print delimiter.join(mylist)
###########################################################
创建一个类:
#!/usr/bin/python
# Filename: simplestclass.py
class Person:
pass # An empty block
p = Person()
print p
###########################################################
使用对象的方法
#!/usr/bin/python
# Filename: method.py
class Person:
def sayHi(self):
print ‘Hello, how are you?‘
p = Person()
p.sayHi()
# This short example can also be written as Person().sayHi()
###########################################################
使用_init_方法:
#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print ‘Hello, my name is‘, self.name
p = Person(‘Swaroop‘)
p.sayHi()
# This short example can also be written as Person(‘Swaroop‘).sayHi()
输出:
$ python class_init.py
Hello, my name is Swaroop
###########################################################
使用类与对象的变量
class Person:
‘‘‘Represents a person.‘‘‘
population = 0
def __init__(self, name):
‘‘‘Initializes the person‘s data.‘‘‘
self.name = name
print ‘(Initializing %s)‘ % self.name
# When this person is created, he/she
# adds to the population
Person.population += 1
def __del__(self):
‘‘‘I am dying.‘‘‘
print ‘%s says bye.‘ % self.name
Person.population -= 1
if Person.population == 0:
print ‘I am the last one.‘
else:
print ‘There are still %d people left.‘ % Person.population
def sayHi(self):
‘‘‘Greeting by the person.
Really, that‘s all it does.‘‘‘
print ‘Hi, my name is %s.‘ % self.name
def howMany(self):
‘‘‘Prints the current population.‘‘‘
if Person.population == 1:
print ‘I am the only person here.‘
else:
print ‘We have %d persons here.‘ % Person.population
swaroop = Person(‘Swaroop‘)
swaroop.sayHi()
swaroop.howMany()
kalam = Person(‘Abdul Kalam‘)
kalam.sayHi()
kalam.howMany()
swaroop.sayHi()
swaroop.howMany()
###########################################################
使用继承:
#!/usr/bin/python
# Filename: inherit.py
class SchoolMember:
‘‘‘Represents any school member.‘‘‘
def __init__(self, name, age):
self.name = name
self.age = age
print ‘(Initialized SchoolMember: %s)‘ % self.name
def tell(self):
‘‘‘Tell my details.‘‘‘
print ‘Name:"%s" Age:"%s"‘ % (self.name, self.age),
class Teacher(SchoolMember):
‘‘‘Represents a teacher.‘‘‘
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print ‘(Initialized Teacher: %s)‘ % self.name
def tell(self):
SchoolMember.tell(self)
print ‘Salary: "%d"‘ % self.salary
class Student(SchoolMember):
‘‘‘Represents a student.‘‘‘
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print ‘(Initialized Student: %s)‘ % self.name
def tell(self):
SchoolMember.tell(self)
print ‘Marks: "%d"‘ % self.marks
t = Teacher(‘Mrs. Shrividya‘, 40, 30000)
s = Student(‘Swaroop‘, 22, 75)
print # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
###########################################################
使用文件:
#!/usr/bin/python
# Filename: using_file.py
poem = ‘‘‘\
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
‘‘‘
f = file(‘poem.txt‘, ‘w‘) # open for ‘w‘riting
f.write(poem) # write text to file
f.close() # close the file
f = file(‘poem.txt‘)
# if no mode is specified, ‘r‘ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print line,
# Notice comma to avoid automatic newline added by Python
f.close() # close the file
###########################################################
存储与取存储:使用它可以在一个文件中存储任何Python对象,之后你又可以完整无缺的取出来
#!/usr/bin/python
# Filename: pickling.py
import cPickle as p
#import pickle as p
shoplistfile = ‘shoplist.data‘
# the name of the file where we will store the object
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘]
# Write to the file
f = file(shoplistfile, ‘w‘)
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist
###########################################################
处理异常:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input(‘Enter something --> ‘)
except EOFError:
print ‘\nWhy did you do an EOF on me?‘
sys.exit() # exit the program
except:
print ‘\nSome error/exception occurred.‘
# here, we are not exiting the program
print ‘Done‘
###########################################################
如何引发异常:
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
‘‘‘A user-defined exception class.‘‘‘
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input(‘Enter something --> ‘)
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print ‘\nWhy did you do an EOF on me?‘
except ShortInputException, x:
print ‘ShortInputException: The input was of length %d, \
was expecting at least %d‘ % (x.length, x.atleast)
else:
print ‘No exception was raised.‘
###########################################################
使用finally:
#!/usr/bin/python
# Filename: finally.py
import time
try:
f = file(‘poem.txt‘)
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,
finally:
f.close()
print ‘Cleaning up...closed the file‘
###########################################################
命令行参数:
#!/usr/bin/python
# Filename: cat.py
import sys
def readfile(filename):
‘‘‘Print a file to the standard output.‘‘‘
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
f.close()
# Script starts from here
if len(sys.argv) < 2:
print ‘No action specified.‘
sys.exit()
if sys.argv[1].startswith(‘--‘):
option = sys.argv[1][2:]
# fetch sys.argv[1] but without the first two characters
if option == ‘version‘:
print ‘Version 1.2‘
elif option == ‘help‘:
print ‘‘‘\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help‘‘‘
else:
print ‘Unknown option.‘
sys.exit()
else:
for filename in sys.argv[1:]:
readfile(filename)
###########################################################
os模块:
os.name字符串指示你正在使用的平台。比如对于Windows,它是‘nt‘,而对于Linux/Unix用户,它是‘posix‘。
os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
os.listdir()返回指定目录下的所有文件和目录名。
os.remove()函数用来删除一个文件。
os.system()函数用来运行shell命令。
os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用‘\r\n‘,Linux使用‘\n‘而Mac使用‘\r‘。
os.path.split()函数返回一个路径的目录名和文件名。
例如获得平台:
#vim get_os.py
#!/usr/bin/python
# Filename:get_os.py
import os
print os.name
###########################################################
在函数中接受元组和列表
>>> def powersum(power, *args):
... ‘‘‘Return the sum of each argument raised to specified power.‘‘‘
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>> powersum(2, 3, 4)
25
>>> powersum(2, 10)
100
###########################################################
lambda语句被用来创建新的函数对象,并且在运行时返回它们。
#!/usr/bin/python
# Filename: lambda.py
def make_repeater(n):
return lambda s: s*n
twice = make_repeater(2)
print twice(‘word‘)
print twice(5)
输出结果:
$ python lambda.py
wordword
10
###########################################################
assert语句用来声明某个条件是真的。
>>> mylist = [‘item‘]
>>> assert len(mylist) >= 1
>>> mylist.pop()
‘item‘
>>> assert len(mylist) >= 1
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
###########################################################
图形软件:
PyQt 这是Qt工具包的Python绑定。Qt工具包是构建KDE的基石。Qt,特别是配合Qt Designer和出色的Qt文档之后,它极其易用并且功能非常强大。你可以在Linux下免费使用它,但是如果你在Windows下使用它需要付费。使用PyQt,你可以在Linux/Unix上开发免费的(GPL约定的)软件,而开发具产权的软件则需要付费。一个很好的PyQt资源是《使用Python语言的GUI编程:Qt版》请查阅官方主页以获取更多详情。
PyGTK 这是GTK+工具包的Python绑定。GTK+工具包是构建GNOME的基石。GTK+在使用上有很多怪癖的地方,不过一旦你习惯了,你可以非常快速地开发GUI应用程序。Glade图形界面设计器是必不可少的,而文档还有待改善。GTK+在Linux上工作得很好,而它的Windows接口还不完整。你可以使用GTK+开发免费和具有产权的软件。请查阅官方主页以获取更多详情。
wxPython 这是wxWidgets工具包的Python绑定。wxPython有与它相关的学习方法。它的可移植性极佳,可以在Linux、Windows、Mac甚至嵌入式平台上运行。有很多wxPython的IDE,其中包括GUI设计器以及如SPE(Santi‘s Python Editor)和wxGlade那样的GUI开发器。你可以使用wxPython开发免费和具有产权的软件。请查阅官方主页以获取更多详情。
TkInter 这是现存最老的GUI工具包之一。如果你使用过IDLE,它就是一个TkInter程序。在PythonWare.org上的TkInter文档是十分透彻的。TkInter具备可移植性,可以在Linux/Unix和Windows下工作。重要的是,TkInter是标准Python发行版的一部分。
###########################################################
个人笔记:
python int 和 string 互转
int --> str 直接使用 str(123); 把123 转成“123” str --> int string.atoi("123") 把“123”转成123