zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python练习3

Python 练习
2023-09-14 09:14:09 时间

1、math库

        3.8请利用math库运行下面的语句,获得计算结果
        3.9请利用math库47°的角转换为弧度制,并将结果献给一个变量
        3.10请利用math库将π/7的弧度制转换为角度值,并将结果赋值一个变量

import math
#3.8请利用math库运行下面的语句,获得计算结果
print(math.sin(2 * math.pi))
print(math.floor(-2.5))
print(math.ceil(3.5 + math.floor(-2.5)))
print(round(math.fabs(-2.5)))
print(math.sqrt(math.pow(2, 4)))
print(math.log(math.e))
print(math.gcd(12, 9))
print(math.fmod(36, 5))

#3.9请利用math库47°的角转换为弧度制,并将结果献给一个变量
print(math.radians(47))

#3.10请利用math库将π/7的弧度制转换为角度值,并将结果赋值一个变量
print(math.degrees(3.14 / 7))

2、两点之间的距离

import turtle as t
import math

print("请输入点A和点B的坐标:")
x1, y1 = eval(input("x1,y1="))
x2, y2 = eval(input("x2,y2="))
dis = math.sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2))
print("点A和点B间的距离为:", dis)

t.penup()
t.goto(x1, y1)
t.pendown()
t.goto(x2, y2)
t.penup()
t.goto((x1 + x2) / 2, (y1 + y2) / 2)
t.pendown()
t.write("dis={}".format(dis), font=("Time", 16, "bold",))
t.done()

3、两点的距离:turtle画图,计算距离

# turtle画图,计算距离
import turtle as t
import math

x1 = int(input("请输入A点的横坐标:"))
y1 = int(input("请输入A点的纵坐标:"))
x2 = int(input("请输入B点的横坐标:"))
y2 = int(input("请输入B点的纵坐标:"))

t.penup()
t.goto(x1, y1)
t.pendown()
t.goto(x2, y2)
x = x1 - x2
y = y1 - y2
if x < 0:
    x = 0 - x
if y < 0:
    y = 0 - y
length = math.sqrt(x * x + y * y)
print(length)
t.goto(int(x1 + x2) / 2, int(y1 + y2) / 2)
t.write("l = {:.2f}".format(length))
t.done

4、字符串

        3.17判断题:Python中“4”+“5”结果为“9”。
        3.19 s = "Python String",写出下列操作的输出结果
        3.20下列表达式错误的是

# 3.16
s = "hello"
t = "world"
s += t
print(s)
print(s[-1])
print(s[2:8])
print(s[::3])
print(s[-2::-1])

# 3.17判断题:Python中“4”+“5”结果为“9”。
print("4" + "5")

# 3.19 s = "Python String",写出下列操作的输出结果
s = "Python String"
print(s.upper())
print(s.lower())
print(s.find('1'))
print(s.replace('ing', 'gni'))
print(s.split(' '))

# 3.20下列表达式错误的是
print('abcd' < 'ad')
print('abc' < 'abcd')
print("< 'a'")
print('Hello' > 'hello')

5、月份数字返回月份名称

        要求:输入月份代表的数字,输出月份的简写。

# 要求:输入月份代表的数字,输出月份的简写。

month = "JanFebMarAprMayJunJulAugSepOctNovDec"  # 将所有月份简写存到month中

n = input("请输入月份代表的数字:")

pos = (int(n) - 1) * 3  # 输入的数字为n,将(n-1)*3,即为当前月份所在索引位置

findmonth = month[pos:pos + 3]

print("月份的简写为:" + findmonth + ".")

6、运算优先级

        3.5思考各操作符的优先级,计算下列表达式
        3.6请将下列数学表达式用Python程序写出来,并运算结果
        3.7假设x=1,x*3+5**2的运算结果是什么?

# 3.5思考各操作符的优先级,计算下列表达式
a = 30 - 3 ** 2 + 8 // 3 ** 2 * 10
b = 3 * 4 ** 2 / 8 % 5
c = 2 ** 2 ** 3
d = (2.5 + 1.25j) * 4j / 2
print("a =", a)
print("b =", b)
print("c =", c)
print("d =", d)

# 3.6请将下列数学表达式用Python程序写出来,并运算结果
x = (2 ** 4 + 7 - 3 * 4) / 5
y = (1 + 3 ** 2) * (16 % 7) / 7
print("x = ", x)
print("y = ", y)

# 3.7假设x=1,x*3+5**2的运算结果是什么?
m = 1
n = m * 3 + 5 ** 2
print("n = ", n)