python的入门的几个例子(上)

在Python for Unix and Linux System Administration列出了几个选择python的理由:

易入门

上手后可进行系统管理
能解决复杂问题
代码简洁,易读
关键字使陌生代码易读
面向对象
社区优秀
很好的标准库

python的基础例子在这里,很有意思,下一个例子的行数是递增的

http://wiki.python.org/moin/SimplePrograms

例1.输出显示–Output

print 'Hello world'

例2.变量以提示输入的方式赋值,并打印出来–Input, assignment

name = raw_input('What is your name?\n')
print 'Hi, %s.' % name

例3.for循环,内置的列举函数,format格式–For loop, built-in enumerate function, new style formatting

friends = ['jhon', 'pat', 'gary', 'micheal']
for i, name in enumerate(friends):
    print "iteration {iteration} is {name}".format(iteration=i, name=name)

例4.斐波纳契,元组的赋值–Fibonacci, tuple assignment

parents, babies = (1, 1)
while babies < 100:
    print 'This generation has {0} babies'.format(babies)
    parents, babies = (babies, parents + babies)

例5.函数–Functions

def greet(name):
    print 'hello', name
greet('Jack')
greet('Jill')
greet('Bob')

例6.import,正则表达式–Import, regular expressions。这里是匹配3位数字-4位数字的字符串。

import re
for test_string in [ '555-1212', 'ILL-EGAL' ]:
    if re.match(r'^\d{3}-\d{4}', test_string):
        print test_string, 'is a valid US local phone number'
    else:
        print test_string, 'rejected'

例7.字典,生成表达式–Dictionaries, generator expressions

prices = { 'apple': 0.40, 'banana': 0.50 }
my_purchase = {
    'apple': 1,
    'banana':6}
grocery_bill = sum(prices[fruit] * my_purchase[fruit]
                   for fruit in my_purchase)
print 'I owe the grocer $%.2f' % grocery_bill

例8.调用命令参数,异常处理–Command line arguments, exception handling

#!/usr/bin/env python
# This program adds up integers in the command line
import sys
try:
    total = sum(int(arg) for arg in sys.argv[1:])
    print 'sum =', total
except ValueError:
    print 'Please supply integer arguments'

上面是将跟的参数相加,如果不是整数,则提示需输入整数

$ python se8.py 1 2 3 4 5 6
sum = 21
$ python se8.py 1 2 3 4 5 a
Please supply integer arguments

例9.打开文件–Opening files

# indent your Python code to put into an email
import glob
# glob supports Unix style pathname extensions
python_files = glob.glob('*.py')
for file_name in sorted(python_files):
print ' ------' + file_name

with open(file_name) as f:
for line in f:
print ' ' + line.rstrip()

print

例10.时间,条件,from..import,for ..else循环 — Time, conditionals, from..import, for..else

from time import localtime

activities = {8: 'Sleeping',
              9: 'Commuting',
              17: 'Working',
              18: 'Commuting',
              20: 'Eating',
              22: 'Resting' }

time_now = localtime()
hour = time_now.tm_hour

for activity_time in sorted(activities.keys()):
    if hour < activity_time:
        print activities[activity_time]
        break
else:
    print 'Unknown, AFK or sleeping!'

整理一些小知识

段落注释的方法

""" """

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注