编译语言:C,java
解释语言:php,javascript, 需要保留源代码,需要解释器 维护方便,可移植性强
Python 中文为蟒蛇
拥有者是Python Software Foundation简称PSF,非盈利组织
1989年诞生 2000年 2.0版本 2008年 3.0版本
Python是 通用语言、脚本语言、开源语言、跨平台语言、多模块语言
Python主页下载安装Python基本开发和运行环境:https://www.python.org/downloads/
启动Python的方法:1、cmd-》Python
2、IDLE
3、保存到文本文件如:hello.py 运行:Python hello.py
print("输出的温度是:%.2fF"%f)
for i in range(<计数值>):
<表达式组>
import turtle
def drawSnake(rad,angle,len,neckrad):
for i in range(len):
turtle.circle(rad,angle) #让小乌龟沿着一个圆形爬行,rad描述圆形轨迹半径的位置这个半径在小乌龟运行的左侧rad远位置处,如果rad为负值,则半径在小乌
turtle.circle(-rad,angle) #龟运行的右侧
turtle.circle(rad,angle/2)
turtle.fd(rad) #也可以用turtle.forward()表示乌龟向前直线爬行移动
turtle.circle(neckrad+1,180)
turtle.fd(rad*2/3)
def main():
turtle.setup(1300,800,0,0) #用于启动一个图形窗口,启动窗口的宽度,高度,窗口左上角在屏幕中的坐标位置
pythonsize=30
turtle.pensize(pythonsize) #表示小乌龟运动轨迹的宽度
turtle.pencolor("blue") #表示小乌龟运动轨迹的颜色采用RGB,同 turtle.pencolor(“#3B9909”)
turtle.seth(-40) #表示小乌龟启动时运动的方向,0表示向东,90度向北,180度向西,270度向南;负值表示相反方向
drawSnake(40,80,5,pythonsize/2)
main()
t1=123,456,("hello","China")
元组中各元素存在先后关系,可以通过索引访问元组中元素。
from random import random
from math import sqrt
from time import clock
DARTS=1200000
hits=0
clock()
for i in range(1,DARTS):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist <=1.0:
hits=hits+1
pi=4*(hits/DARTS)
print("Pi的值是%s"%pi)
print("程序运行时间为%-5.5ss"%clock())
DARTS值越大,π值越精确
>>>"{}{}{}".format(" 圆周率是",3.1415926,"...")
'圆周率是 3.1415926...'
>>>" 圆周率{{{1}{2}}} 是{0}".format(" 无理数",3.1415926,"...")
'圆周率{3.1415926...}是无理数'
>>>s=" 圆周率{{{1}{2}}} 是{0}" # 大括号本身是字符串的一部分
>>>s
'圆周率{{{1}{2}}}是{0}'
>>>s.format(" 无理数",3.1415926,"...") # 当调用 format() 时解析大括号
'圆周率{3.1415926...}是无理数'
>>>s = "PYTHON"
>>>"{0:30}".format(s)
'PYTHON '
>>>"{0:>30}".format(s)
' PYTHON'
>>>"{0:*^30}".format(s)
'************PYTHON************'
>>>"{0:-^30}".format(s)
'------------PYTHON------------'
>>>"{0:3}".format(s)
'PYTHON'
>>>"{0:-^20,}".format(1234567890)
'---1,234,567,890----'
>>>"{0:-^20}".format(1234567890) # 对比输出
'-----1234567890-----'
>>>"{0:-^20,}".format(12345.67890)
'----12,345.6789-----'
>>>"{0:.2f}".format(12345.67890)
'12345.68'
>>>"{0:H^20.3f}".format(12345.67890)
'HHHHH12345.679HHHHHH'
>>>"{0:.4}".format("PYTHON")
'PYTH'
>>>"{0:b},{0:c},{0:d},{0:o},{0:x},{0:X}".format(425)
'110101001,Ʃ,425,651,1a9,1A9'
>>>"{0:e},{0:E},{0:f},{0:%}".format(3.14)
'3.140000e+00,3.140000E+00,3.140000,314.000000%'
>>>"{0:.2e},{0:.2E},{0:.2f},{0:.2%}".format(3.14)
'3.14e+00,3.14E+00,3.14,314.00%'
try:
except :
except :
except:
Python的异常处理语句还可以使用else和finally关键字
try:
except :
except :
except:
else:
finally:
如:
def main():
try:
number1,number2=eval(input("Enter two numbers,separated by a comma:"))
result=number1/number2
except ZeroDivisionError:
print("Division by zero!")
except SyntaxError:
print("A comma may be missing in the input")
except:
print("Something wrong in the input")
else:
print("No exception, the result is",result)
finally:
print("executing the final clause")
main()
如:
import math
def main():
print("This program finds the real solutions to a quadratic.\n")
try:
a,b,c=eval(input("Please enter the coefficients(a,b,c):"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root2=(-b-discRoot)/(2*a)
print("\nThe solution are:",root1,root2)
except ValueError as excObj:
if str(excObj)=="math domain error":
print("No Real Roots.")
else:
print("You didn't give me the right number of coefficients.")
except NameError:
print("\nYou didn't enter three numbers.")
except TypeError:
print("\nYour inputs were not all numbers.")
except SyntaxError:
print("\nYour input was not in the correct form. Missing comma?")
except:
print("\nSomething went wrong,sorry!")
main()
n=eval(input("How many numbers?"))
sum=0.0
for i in range(n):
x=eval(input("Enter a number>>"))
sum=sum+x
print("\nThe average is",sum/n)
for循环-缺点
for n in range(2,10):
for x in range(2,n):
if n%x==0:
print(n,'equals',x,'*',n//x)
break
else:
print(n,'is a prime number')
def main():
sum=0.0
count=0
moredata="yes"
while moredata[0]=="y":
x=eval(input("Enter a number>>"))
sum=sum+x
count=count+1
moredata=input("Do you have more numbers(yes or no)?")
print("\nThe average of the number is",sum/count)
main()
哨兵循环:
def main():
sum=0.0
count=0
x=eval(input("Enter a number(negative to quit)>>"))
while x>0:
sum=sum+x
count=count+1
x=eval(input("Enter a number(negative to quit)>>"))
print("\nThe average of the number is",sum/count)
main()
改进:
def main():
sum=0.0
count=0
xStr=input("Enter a number( to quit)>>")
while xStr!="":
x=eval(xStr)
sum=sum+x
count=count+1
xStr=input("Enter a number( to quit)>>")
print("\nThe average of the number is",sum/count)
main()
文件循环
def main():
fileName=input("What file are the numbers in?")
infile=open(fileName,'r')
sum=0.0
count=0
for line in infile:
sum=sum+eval(line)
count=count+1
print("\nThe average of the number is",sum/count)
main()
def main():
fileName=input("What file are the numbers in?")
infile=open(fileName,'r')
sum=0.0
count=0
line=infile.readline()
while line !="":
sum=sum+eval(line)
count=count+1
line=infile.readline()
print("\nThe average of the number is",sum/count)
main()
循环嵌套
def main():
fileName=input("What file are the numbers in?")
infile=open(fileName,'r')
sum=0.0
count=0
line=infile.readline()
while line !="":
for xStr in line.split(","):
sum=sum+eval(xStr)
count=count+1
line=infile.readline()
print("\nThe average of the number is",sum/count)
main()
while True:
try:
x=int(input("Please enter a number"))
except ValueError:
print("Oops,that was no valid number.Try again...")
break
def happy():
print("Happy birthday to you!")
def sing(person):
happy()
happy()
print("Happy birthday,dear "+person+"!")
happy()
def main():
sing("Mike")
print()
sing("Lily")
print()
sing("Elemer")
main()
def reverse(s):
if s=="":
return s
else:
return reverse(s[1:])+s[0]
def main():
print(reverse("Hello"))
main()
# drawtree.py
from turtle import Turtle, mainloop
def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 5: #
lst = []
for p in plist:
p.forward(l)#沿着当前的方向画画Move the turtle forward by the specified distance, in the direction the turtle is headed.
q = p.clone()#Create and return a clone of the turtle with same position, heading and turtle properties.
p.left(a) #Turn turtle left by angle units
q.right(a)# turn turtle right by angle units, nits are by default degrees, but can be set via the degrees() and radians() functions.
lst.append(p)#将元素增加到列表的最后
lst.append(q)
tree(lst, l*f, a, f)
def main():
p = Turtle()
p.color("green")
p.pensize(5)
#p.setundobuffer(None)
p.hideturtle() #Make the turtle invisible. It’s a good idea to do this while you’re in the middle of doing some complex drawing,
#because hiding the turtle speeds up the drawing observably.
#p.speed(10)
# p.getscreen().tracer(1,0)#Return the TurtleScreen object the turtle is drawing on.
p.speed(10)
#TurtleScreen methods can then be called for that object.
p.left(90)# Turn turtle left by angle units. direction 调整画笔
p.penup() #Pull the pen up – no drawing when moving.
p.goto(0,-200)#Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation.
p.pendown()# Pull the pen down – drawing when moving. 这三条语句是一个组合相当于先把笔收起来再移动到指定位置,再把笔放下开始画
#否则turtle一移动就会自动的把线画出来
#t = tree([p], 200, 65, 0.6375)
t = tree([p], 200, 65, 0.6375)
main()
import turtle #或者
from turtle import * #下文中提到的“第二种方式”