免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2160 | 回复: 0
打印 上一主题 下一主题

python 基础学习 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-03-22 21:45 |只看该作者 |倒序浏览

参数和数学计算:
  
#!C:\\python26\\python.exe
#Name: jisuan.py
#eg: 1+2+3+4+...+x
import math
import sys
if len(sys.argv) != 2:
        print "Usage: "+sys.argv[0]+" 10000"
else:
    sumx=0
    x=int(sys.argv[1])
    for i in range(0,x+1,1):
        sumx=sumx+i
    print sumx



交互的用法:
#!C:\\python26\\python.exe
NAME=raw_input ("Please input your name here: ")
print "Your name is " + NAME + "!"



调用系统命令:

Linux:
----------------------
#!/usr/bin/python
import os
print "\n"
os.system('ls')
print "\n\n"
os.system(''' ifconfig|grep 192|awk '{print $2}'|awk -F: '{print $2}' ''')
Windows:
----------------------
import os
os.system('ping 127.0.0.1')
os.system('ipconfig')

列表和range:

word=list("zhaohang")
for w in word:
    print w
print "\n"
for i in range(0,31,5):
    print i,



while、if、try 判断是否数字:

print 'Could you guess me ? I am a int number!'
running=True
while running:
    try:
        NUM=287
        GUESS=int(raw_input('Begin to guess me: '))
        if GUESS == 287:
            print 'Eo, you guess right. You are verry clever!'
            running = False
        elif GUESS  287:
            print 'It\'s too small!'
        else:
            print 'It\'s too big!'
    except ValueError:
        print "You must input a number!"


判断是否纯数字的函数:

#!/usr/bin/env python
GUESS=raw_input('Begin to guess me: ')
if GUESS.isdigit():
    print "OK"
else:
    print "It's not a number!"
说明:判断变量是否纯数字的方法一种是 变量.isdigit() ,为真说明纯数字,但这种方法对于包含正负号的数字字符串无效,这时可以用: ValueError: 如上面实例!



程序中quit来控制退出:

while True:
    GUESS = raw_input("Please input a string: ")
    if GUESS == "quit":
        break
    if len(GUESS) = 3:
        continue
    else:
        print "Your are input: " + GUESS + " !"



帮助函数:

def USAGE():
    print '''\
This script is a example for function. (HanShu)
It will get a simple usage for us!
Usage: file.py 100
    --help: print this text.
    --version: 2.6
'''
# Call the function.
USAGE()

自定义函数:
def maxnum(x,y):
    if x > y:
        print x,"is the max number!"
    else:
        print y,"is the max number!"
x = float(raw_input("Please input the first number: "))
y = float(raw_input("Please input the second number: "))
maxnum(x,y)
def func(a=0):
    print "a =",a
func()
func(5)

函数的返回值:
def func(a,b):
    if a > b:
        return a
    else:
        return b
a = int(raw_input("The first number: "))
b = int(raw_input("The second number: "))
print "The max number is: ",func(a,b)

pass(空语句块)、continue(返回执行)、break(中断跳出循环)、sys.exit()退出程序:
while True:
    a = input("Please input a number: ")
    if a > 80:
        pass
        break
    else:
        continue

自定义模块的创建和应用:
# filename: zhaohang_hi_module.py
def sayhi():
    print 'Hi! This is my module speaking!'
version = 'V1.00'
调用:
import zhaohang_hi_module
zhaohang_hi_module.sayhi()
print "My module version is:",zhaohang_hi_module.version

或:
from zhaohang_hi_module import sayhi
sayhi()

递归查找文件os.walk:

#!/bin/env python
import os,sys
for root,dirs,files in os.walk('/etc'):
    if sys.argv[1] in files:
       #print root
       #print files
       #print dirs
       print os.path.join(root,sys.argv[1])

字典学习:
#!/usr/bin/env python
import sys
dic_file = open('/root/dic.txt','r')
dic = {}
for line in dic_file.readlines():
    (key, value) = line.split()
    dic[key] = value
dic_file.close()
print dic.get(sys.argv[1])
#print dic.items()
#print dic.values()

文件字符串替换:
#/etc/env python
import re,string
f='/root/test.txt'
files=open('%s'%(f),'rw')
file=files.readlines()
files.close()
F = open('%s'%(f),'w')
for i in file:
  f1= i.replace('zhaohang','Droney')
  F.write(f1)
F.close()

输入字符串反向输出:
#!/bin/env python
import sys
newStr=''
x=len(sys.argv[1])
for y in range(x):
    newStr=newStr+sys.argv[1][x-1-y]
print newStr
或:
str = raw_input('Please input:')
print str[::-1]



综合应用:

import sys
def readfile(filename):
    f = file(filename)
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print line
    f.close()
if len(sys.argv)  2:
    print "No action!"
    sys.exit()
if sys.argv[1].startswith('--'):
    option = sys.argv[1][2:]
    if option == 'version':
        print 'Version 2.6'
    elif option == 'help':
        print '''
This Script will print the file you wan't to see, It like the "cat" in
Any number of files could be specified.
Options include:
    --version: Print the verison of your Python.
    --help: Display this help.
'''


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93470/showart_1871957.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP