以下为《python的函数应用》的无排版文字预览,完整格式请下载
下载前请仔细阅读文字预览以及下方图片预览。图片预览是什么样的,下载的文档就是什么样的。
python的函数应用
一、函数的作用:
1)实现特定功能;2)代码复用
二、函数类别:
1.内置函数:事先已经定义好的函数,可直接调用。
如abs(x),input(),int(),ord()
2.外调函数:从外部引入函数模块后,进行相应函数调用,包括一些常用的标准函数,和各类扩展函数
如:import math as t
可用dir(math)查看有哪些函数
可用help(math)查看有哪些函数及详细用法
如t.sqrt(x),t.sin(3.14*30/180)
如:import turtle as t
t.fd(100),t.rt(90)
3.自定义函数:通过def自主定义后,在后面进行调用。
三、函数的定义
def (): #所指定的参数是一种占位符,作为输入
return #输出
例1: def add(x,y):
z=x+y
return z
例2:
import turtle as t
def polygon(n):
for i in range(n):
t.fd(50)
t.rt(360/n)
四、函数的调用:
函数名(实参)
例1调用:上面add()函数的调用。
print(add(2,3))
kk=add(4,6)
print(kk)
例2调用:
for x in range(3,10):
polygon(x)
五、应用练习:
练习1:定义一个函数实现把一个正整数的各位数字求和。
定义函数he(x):
def he(x):
s=0
while x>0:
s=____
x=x//10
return ___
调用:
x=int(input("x="))
print(he(x))
练习2:把一个十进制正整数转化为二进制数的字符串表达。(除2取余倒读法)
定义函数zh(x):
def zh(x):
s=""
while x>0:
s=chr(48+x%2)+s
x=____
return s
调用:
x=int(input("x="))
print(zh(x))
练习3:定义一个判断正整数x是否是素数的 内容过长,仅展示头部和尾部部分文字预览,全文请查看图片预览。 dir用1和-1来设置方向,左右眼对称
t.penup()
t.goto((0-dir)*30, 90)
t.setheading(90)
t.pendown()
t.fillcolor('#f2ae20')
t.begin_fill()
t.circle(dir*30)
t.end_fill()
t.penup()
t.goto((0-dir)*40, 85)
t.setheading(90)
t.pendown()
t.fillcolor('white')
t.begin_fill()
t.circle(dir*17)
t.end_fill()
def nose(): # 画鼻子
t.penup()
t.goto(20, 0)
t.setheading(90)
t.pendown()
t.fillcolor('#a2774d')
t.begin_fill()
t.circle(20)
t.end_fill()
def eye(dir): # 画耳朵,dir用1和-1来设置方向,左右耳对称
t.penup()
t.goto((0-dir)*30, 20)
t.setheading(0)
t.pendown()
t.fillcolor('black')
t.begin_fill()
t.circle(10)
t.end_fill()
def mouth(): # 画嘴巴
t.penup()
t.goto(0, 0)
t.setheading(-90)
t.pendown()
t.forward(50)
t.setheading(0)
t.circle(80, 30)
t.penup()
t.goto(0, -50)
t.setheading(180)
t.pendown()
t.circle(-80, 30)
#调用:
ears(1)
ears(-1)
face()
eye(1)
eye(-1)
mouth()
nose()
[文章尾部最后300字内容到此结束,中间部分内容请查看底下的图片预览]请点击下方选择您需要的文档下载。
以上为《python的函数应用》的无排版文字预览,完整格式请下载
下载前请仔细阅读上面文字预览以及下方图片预览。图片预览是什么样的,下载的文档就是什么样的。