Python之函数

一.内置函数-让你偷懒的工具
定义函数prime,功能是判断整数n是否为素数;
若整数n是素数则返回True,不是素数则返回False。

#coding=utf-8 
#输入一个整数n
n =  int(input())
 # 请在此添加代码,实现编程要求********** Begin *********
def prime(n):    
if n == 1:       
 return False    
 else:       
  for i in range(2, n):                      
     if n % i == 0:                            
     return False                    return True            #**********End**********#
  print(prime(n))

二.外置函数numpy-科学计算工具
第一题:
绘制如下函数组的曲线(花形),角度属于[0, 2pi]。x=sin(10θ)cos(θ)y=sin(10θ)sin(θ)第二题绘制如下函数的函数型曲线,角度属于[0, 2pi]。x=16(sinθ) 3 y=13cosθ−5cos2θ−2cos3θ−cos4θ

import numpy as np
importmatplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # 第一题
#x = sin(10\theta)cos(\theta)
#y=sin(10\theta)sin(\theta)
theta=np.linspace(0,2*np.pi,1000)
############ begin ##########
#求出2pi区间下均匀分布的1000个点x=np.sin(theta)*np.cos(theta)
############end############
y=np.sin(10*theta)*np.sin(theta)plt.plot(x,y,'r')
plt.savefig('./src/step4/ans1/轨迹1.png')
print(x[0])plt.close() 
 # 第2题
 # 求2pi区间下均匀分布的100个点
 t = np.linspace(0, 2*np.pi,100)
 x =16*np.sin(t)**3
 # 求y值,并直接输出
 ############begin##########
 y=13*np.cos(t)-5*np.cos(2*t)-2*np.cos(3*t)np.cos(4*t)
 ############end############
 print(y[0])
 plt.plot(x,y,'r')
 plt.axis([-25,25,-20,15])
 plt.savefig('./src/step4/ans1/轨迹2.png')
 plt.close() 

三.函数正确调用-得到想要的结果
定义函数bubbleSort,对参数(一个数值列表)进行从小到大顺序排序;
函数返回排序后的数值列表。

#coding=utf-8 
#输入数字字符串,并转换为数值列表
a = input()
num1 = eval(a)
numbers = list(num1) 
# 请在此添加函数bubbleSort代码,实现编程要求
#**********Begin*********#
result =sorted(numbers)
print(result)   
#********** End **********#

四.函数与函数调用-分清主次
定义函数circle_area,要求实现圆的面积计算;
函数需要根据半径的不同值采取不同处理过程,若半径值为合法数值,则返回圆面积(圆面积四舍五入后保留两位小数);否则在函数中直接打印输出“You must input an integer or float as radius.”。

#coding=utf-8 
from math import pi as PI
 n = int(input()) 
 # 请在此添加函数circle_area的代码,返回以n为半径的圆面积计算结果#********** Begin *********#
 def circle(n):    
 return PI*n*n
 s=circle(n)print('%.2f'%s)
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值