目标:
基本数据类型和函数操作
内容:
- 请利用math模块把角度制60度转换成弧度制,并计算其对应的余弦值。
- 用户键入一个字符串s(如“hello Python”),请将其反转后进行输出。
步骤:
题1.请利用math模块把角度制60度转换成弧度制,并计算其对应的余弦值。
代码如下:
#-*-coding: utf-8-*-
import math
a+math.cos(math.pi/3)
b=math.radians(60)
print(a,b)
运行结果:
题2.用户键入一个字符串s(如“hello Python”),请将其反转后进行输出。
方法一:使用方法为字符串切片——字符串反转最简单方法
代码如下:
s='hello python'
print(s[::-1])
运行结果:
结果检验:
方法二:使用递归函数
代码如下:n=‘hello Python’
#-*-coding: utf-8-*-
def f(n):
if len(n)<1:
return n
return f(n[1::])+n[0]
printf('hello python')
运行结果:
扩展
弧度制与角度制之间的转换:
(1)在python中使用三角函数时,不能直接使用,要先导入math模块;
(2)在计算对应角度的三角函数需先将角度换成弧度再进行计算。
Python实现字符串反转方法:
第一种:使用字符串切片
result = s[::-1]
第二种:使用列表的reverse方法
l = list(s)
result = “”.join(l.reverse())
或者
l = list(s)
result = “”.join(l[::-1])
第三种:使用reduce
result = reduce(lambda x,y:y+x,s)
第四种:使用递归函数
def func(s):
if len(s) <1:
return s
return func(s[1:])+s[0]
result = func(s)
第五种:使用栈
def func(s):
l = list(s) #模拟全部入栈
result = “”
while len(l)>0:
result += l.pop() #模拟出栈
return result
result = func(s)
第六种:for循环
def func(s):
result = “”
max_index = len(s)-1
for index,value in enumerate(s):
result += s[max_index-index]
return result
result = func(s)