python例子
例一:for循环
for i in range(1,100):
if i==23:
print "great,%s you got your lucky number:" %(i)
break
else:
print 'the number is :',i
运行:windows下 切换到目录下 Python xunhuan.py
linux 下 cd到目录下 Python xunhuan.py
例二:阶乘的例子
n=int(input('Enter an integer >=0:'))
fact=
for i in range(,n+):
fact=fact*i;
print(str(n)+'factorial is'+str(fact))
例三:while循环
total=
s=raw_input('Enter a number(or done):')
while s !='done':
num=int(s)
total=total+num
s=raw_input('Enter a number(or done):')
print('The sum is '+str(total))
例四:九九乘法表
for i in range(,):
for j in range(,i+):
print j, 'x', i, '=', j*i, '\t',
print '\n'
print 'done'
例五、函数定义
import math
def move(x,y,step,angle=):
nx=x+step*math.cos(angle)
ny=y+step*math.sin(angle)
return nx,ny
x, y = move(, , , math.pi / )
print x,y
例六、可变参数函数
import math
def calc(*numbers):
sum =
for n in numbers:
sum = sum + n * n
return sum
y=calc(, ,,)
print y
例七:递归函数
def fact(n):
if n==:
return
return n*fact(n-) y=fact()
print y
例八:尾递归的递归函数
只返回函数本身
def fact(n):
return fact_iter(, , n) def fact_iter(product, count, max):
if count > max:
return product
return fact_iter(product * count, count + , max) y=fact()
print y
例九:高阶函数
def add(x, y, f):
return f(x) + f(y)
print add(-, , abs)
把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。
例十:字典
color={'red':,'blue':,'gree':}
print color['gree']
color['gree']=
print color
例十一:一个ping程序
import subprocess cmd="cmd.exe"
begin=
end=
while begin<end: p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
p.stdin.write("ping 10.10.0."+str(begin)+"\n") p.stdin.close()
p.wait()
begin=begin+ print "execution result: %s"%p.stdout.read()
例十二:os模块
#!/usr/bin/env python
# -*- coding:gbk -*-
import os
for fileName in os.listdir ( 'd:\\' ):
print fileName
例十三:创建目录
#!/usr/bin/env python
# -*- coding:gbk -*-
#Python对文件系统的操作是通过os模块实现
import os
for fileName in os.listdir ( 'd:\\' ):
print fileName
print "**************"
os.mkdir("d:\\dgx")
for fileName in os.listdir ( 'd:\\' ):
print fileName
例十四:写入读取的内容到文件
#!/usr/bin/env python
import os
ls=os.linesep
while True:
fname = raw_input('Enter file name: ')
if os.path.exists(fname):
print "Error:%s already exists "
else:
break
all = [] print "\nEnter lines('.'by itself to quit)" while True:
entry=raw_input('>')
if entry =='.':
break
else:
all.append(entry) fobj=open(fname,'w')
fobj.write('\n'.join(all))
fobj.close()
print 'Done'
例十五:读取文件内容
#!/usr/bin/env python
fname=raw_input('Enter filename:')
try:
fobj=open(fname,'r')
except IOError,e:
print "*******file open error:",e
else:
for eachLine in fobj:
print eachLine,
fobj.close()
例十六:第一个main
#-*-coding:utf--*-
import sys
def Main():
sys.stdout.write("开始程序\n")
str1='i am "python"\n'
str2="i am 'python'\r"
str3="""
i'm "python",
<a href="http://www.sina.com.cn"></a>
"""
print str1,str2,str3
if __name__ == '__main__':
Main()
例十七:函数的默认参数与返回值
#-*-coding:utf--*-
import sys
def arithmetic(x=,y=,operator="+"):
result={
"+":x+y,
"-":x-y,
"*":x*y,
"/":x/y
}
return result.get(operator)
if __name__=="__main__":
print arithmetic(, )
print arithmetic(, , "/")
python例子的更多相关文章
- Docker Python 例子
版权所有,未经许可,禁止转载 章节 Docker 介绍 Docker 和虚拟机的区别 Docker 安装 Docker Hub Docker 镜像(image) Docker 容器(container ...
- 【入门必看】不理解「对象」?很可能有致命bug:简单的Python例子告诉你
简介:越来越多的人要在学习工作中用到『编程』这个工具了,其中很大一部分人用的是Python.大部分人只是做做简单的科研计算.绘图.办公自动化或者爬虫,但-- 这就不需要理解「指针与面向对象」了吗? 在 ...
- python 学习笔记:python例子
廖雪峰python网站 #if els # -*- coding: utf-8 -*- #list是一种有序的集合,可以随时添加和删除其中的元素. ''' classmates=['a','b','c ...
- python例子三
例一:匹配长度为1-15的域名 #-*-encoding:utf--*- import re regex=re.compile('^www[.][a-z]{1,15}[.](com|org)') m1 ...
- Python例子二
例1.构造函数 #-*-coding:utf--*- import sys class Student: def __init__(self,name,age): self.__name=name s ...
- Python 23种设计模式全(python例子)
从今年5月份开始打算把设计模式都写到博客里,持续到现在总算是写完了.写的很慢,好歹算是有始有终.对这些设计模式有些理解的不准确,有些甚至可能是错的,请看到的同学拍砖留言.内容来源很杂,大部分参考或者摘 ...
- Python学习笔记——部分常用/特殊用法
1.使用*号来展开序列,*是序列展开,每个元素都当做一个参数.ls = (1, 2, 3);foo(ls),这样foo只有一个参数,就是ls这个列表本身foo(*ls), foo得到3个参数,分别为1 ...
- Python模拟C++输出流
看到一Python例子,挺有意思的,用Python模拟C++的输出流OStream.单纯只是玩. 原理: 利用Python __lshift__左移内建函数<<,调用时将输出内容,如果内容 ...
- [Python] Symbol Review
From:http://learnpythonthehardway.org/book/ex37.html 1. with X as Y: pass 1.1 yield 2. exec 2.1 name ...
随机推荐
- unity中的main方法
由于方法命名的原因,无意之间把一个方法命名为了Main,然后把这个方放到了Start方法中去执行,结果运行后发现这个方法竟然执行了两次 情况如下图: -------------- 检查代码,发现脚本并 ...
- 习题:过路费(kruskal+并查集+LCA)
过路费 [问题描述]在某个遥远的国家里,有 n 个城市.编号为 1,2,3,…,n.这个国家的政府修 建了 m 条双向道路,每条道路连接着两个城市.政府规定从城市 S 到城市 T 需 要收取的过路费 ...
- [kuangbin带你飞]专题十一 网络流个人题解(L题留坑)
A - ACM Computer Factory 题目描述:某个工厂可以利用P个部件做一台电脑,有N个加工用的机器,但是每一个机器需要特定的部分才能加工,给你P与N,然后是N行描述机器的最大同时加工数 ...
- vue中scoped vs css modules
注意:此文是默认你已经具备scoped和css modules的相关基础知识,所以不做用法上的讲解. 在vue中,我们有两种方式可以定义css作用域,一种是scoped,另一种就是css module ...
- 二叉树节点个数,叶子个数,第K层个数,最低公共节点
1. 节点个数 function getNodeNum(root){ if(root == null){ return 0; } //+1为root的计数 return getNodeNum(root ...
- 使用 Nginx 过滤网络爬虫
现在有许多初学者学习网络爬虫,但他们不懂得控制速度,导致服务器资源浪费.通过 Nginx 的简单配置,能过滤一小部分这类爬虫. 方法一:通过 User-Agent 过滤 Nginx 参考配置如下: l ...
- input上传多张图片
input的file上传多张图片的时候,用ajaxupload这个插件的时候,每次执行完,需要重新生成元素再绑定事件
- codeforces round373(div.2) 题解
这一把打得还算过得去... 最大问题在于A题细节被卡了好久...连续被hack两次... B题是个规律题...C题也是一个细节题...D由于不明原因标程错了被删掉了...E是个线段树套矩阵... 考试 ...
- 30+ Excellent Windows Phone 7 Development Tutorials
原文发布时间为:2012-01-16 -- 来源于本人的百度文章 [由搬家工具导入] Here are 30+ cool Windows Phone Development articles for ...
- 本机开发Native Development:Invalid path for NDK (转)
打开window菜单下的preference选项.选择Android,Native Development(本地开发) 选择你的NDK安装目录.但是,这个插件目前仅支持ndk的r4和r5版本,更高版本 ...