计算复利
a = float(input("请输入本金:"))
b = float(input("请输入年利率:"))
c = float(input("请输入年数:"))
amount = a * (1 + b/100) ** c
print("本金利率和为%.2f" % amount)
计算球的表面积和体积
import math
r = float(input("请输入球的半径:"))
s = 4 * math.pi * r ** 2
v = 4 / 3 * math.pi * r ** 3
print(str.format("球的表面积为:{0:2.2f},体积为{1:2.2f}",s, v))
print("球的表面积为:{0:.2f},体积为{1:.2f}".format(s, v))
复利函数
def getValue(b,r,n):
return b*(1+r/100)**n
b = float(input())
r = float(input())
n = float(input())
amount = getValue(b,r,n)
print("本金利率和为:{0:.2f}".format(amount))
解方程
解方程
import math
a = 1
b = -10
c = 16
delta = pow(b, 2) - 4 * a * c
if delta < 0:
print("次方程无解")
else:
x1 = (-b + math.sqrt(delta)) / (2 * a)
x2 = (-b - math.sqrt(delta)) / (2 * a)
print("方程x*x-10*x+16=0的解为:{0:.1f}{1:.1f}".format(x1,x2))
输出姓名和年龄
输出姓名和年龄
name = input("请输入你的姓名:")
birthyear = int(input("请输入你的出生年份:"))
import datetime
nowyear = datetime.datetime.now().year
age = nowyear - birthyear
print("您好!{0}。您{1}岁。".format(name, age))
算分段函数
import math
x = float(input())
ans = 0
if x >= 0:
ans = math.sin(x) + 2 * math.sqrt(x + math.e ** 4) - (x + 1) ** 3
else:
ans = math.log(-5 * x) - math.fabs(x ** 2 - 8 * x) / (7 * x) + math.e
# 是否为闰年
y = int(input())
if (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0):
print("是闰年")
else:
print("不是闰年")
求自然数e的值
t = 1
e = 1
i = 1
while (1 /t) >= pow(10, -6):
t *= i
e += 1/t
i += 1
print(e)
打印九九乘法表
# 矩形打印九九乘法表
for i in range(1, 10):
for j in range(1, 10):
print("{0}*{1}={2:<3}".format(i, j, i*j), end='')
print()
# 左上三角
for i in range(1, 10):
for j in range(1, i+1): # 注意i+1
print("{0}*{1}={2:<3}".format(i, j, i*j), end='')
print()
# 左下三角
for i in range(1, 10):
for j in range(i, 10):
print("{0}*{1}={2:<3}".format(i, j, i*j), end='')
print()
# 右上三角
for i in range(1, 10):
for j in range(1, 10):
if j >= i:
print("{0}*{1}={2:<3}".format(i, j, i*j), end='')
else:
print(" ",end='')
print()
# 右下三角
for i in range(1, 10):
for j in range(9, 0,-1):
if j <= i:
print("{0}*{1}={2:<3}".format(i, j, i*j), end='')
else:
print(" ",end='')
print()
斐波那契数列
f1 = 1
f2 = 1
for i in range(1, 11):
print(str.format("{0:6}{1:6}", f1, f2), end='')
if i % 2 == 0:
print()
f1 += f2
f2 += f1
是否能构成三角形
import math
# 是否能构成三角形
a = float(input("请输入三角形的边A"))
b = float(input("请输入三角形的边B"))
c = float(input("请输入三角形的边C"))
s = 0
if a > 0 and b > 0 and c > 0:
if a + b > c and b + c > a and c + a > b:
h = (a + b + c) / 2
s = math.sqrt(h * (h - a) * (h - b) * (h - c))
print("三角形三边分别为:{0:.1f},{1:.1f}{2:.1f}".format(a, b, c))
print("三角形周长:{0:.1f},".format(a+b+c), end='')
print("三角形面积:{0:.1f}".format(s))
计算分段函数
import math
x = float(input("请输入x"))
y = 0
if x >= 0:
y = (x*x - 3*x)/(x + 1) + 2*math.pi + math.sin(x)
else:
y = math.log(-5 * x) + 6*math.sqrt(math.fabs(x) + math.e**4) - (x + 1) ** 3
print(y)
求方程的解
import math
a = float(input("请输入系数a:"))
b = float(input("请输入系数b:"))
c = float(input("请输入系数c:"))
x = 0
if a == 0 and b == 0:
print("此方程无解")
elif a == 0 and b != 0:
x = -c / b
print("此方程的解为:{0:.1f}".format(x))
else:
if b ** 2-4 * a * c == 0:
x = -b / (2 * a)
print("此方程有两个相等实根:{0:.1f}".format(x))
elif b ** 2-4 * a * c > 0:
x1 = (-b + math.sqrt(b ** 2-4 * a * c)) / (2 * a)
x2 = (-b - math.sqrt(b ** 2-4 * a * c)) / (2 * a)
print("此方程有两个不等实根:{0:.1f}和{1:.1f}".format(x1, x2))
else:
x1 = -b / (2 * a)
x2 = math.sqrt(4 * a * c - b ** 2) / (2 * a)
print("此方程有两个共轭复根:{0:.1f}+{1:.1f}i和{0:.1f}-{1:.1f}i".format(x1, x2))
求n的阶乘
n = -1
while n < 0:
n = int(input("请输入非负整数n"))
if n == 0:
print(str.format("{0}!={1}".format(n, 1)))
else:
s = 1
for i in range(1, n+1):
s *= i
print(str.format("for循环 {0}!={1}",n, s))
k = 1
temp = n
while temp > 0:
k = k * temp
temp -= 1
print(str.format("while循环 {0}!={1}",n, k))
最小公约数和最大公倍数
import random
x1 = random.randint(0, 100)
x2 = random.randint(0, 100)
print(str.format("整数1={0}整数2={1}", x1, x2))
a, b = x1, x2
while b != 0:
r = a % b
a = b
b = r
b = x1 * x2 // a
print(str.format("最大公约数={0},最小公倍数={1}", a, b))
格式化字符串变量
score, width, precision = 12.34567, 10, 4
print(f"result:{score: {width}.{precision}}")
杨辉三角
n = int(input())
data = [[1], [1, 1]]
for i in range(2, n):
d = [1]
for j in range(i-1):
d.append(data[i-1][j] + data[i-1][j+1])
d.append(1)
data.append(d)
c1 = 6
for i in data:
s = ''
for j in i:
s += ' '
s += str(j)
print(s.center(20))
求直角三角形的两个锐角度数
import math
A = 0
while A <= 0:
A = float(input("请输入直角三角形的直角边:"))
B = 0
while B <= 0:
B = float(input("请输入直角三角形的直角边:"))
C = math.sqrt(A ** 2 + B ** 2)
print("直角三角形三边分别为:a={0:.1f},b={1:.1f},c={2:.1f}".format(A, B, C))
print("三角形的周长={0:.1f},面积={1:.1f}".format(A+B+C, A * B / 2))
h1 = math.asin(A / C)
h2 = math.asin(B / C)
d1 = round(h1 * 180 / math.pi)
d2 = round(h2 * 180 / math.pi)
print("两个锐角的度数分别为:{0:.1f}和{1:.1f}".format(d1, d2))
生成随机数并排序
import random
a = random.randint(0, 100)
b = random.randint(0, 100)
c = random.randint(0, 100)
print("原始值:a={0},b={1},c={2}".format(a, b, c))
if a > b:
a, b = b, a
if a > c:
a, c = c, a
if b > c:
b, c = c, b
print("升序值:a={0},b={1},c={2}".format(a, b, c))
鸡兔同笼
s = int(input("请输入总头数:"))
f = 1
while f % 2 != 0:
f = int(input("请输入总脚数(必须是偶数):"))
flag = 0
for i in range(0, s+1):
j = s - i
if 2 * i + 4 * j == f:
flag = 1
print("方法一:鸡有{0}只兔有{1}只".format(i, j))
break
if flag == 0:
print("无解,请重新运行测试!")
y = (f - 2 * s) // 2
if y < 0:
print("无解,请重新运行测试!")
else:
x = s - y
print("方法二:鸡有{0:}只兔有{1}只".format(x, y))
计算e的x次幂
import math
x = float(input("请输入x:"))
i = 1
s = 1
j = 1
t = 1
while math.fabs(i) >= 1e-10:
t *= j
i = (x ** j) / t
s += i
j += 1
print("Pow(e,x) = {0}".format(s))
迭代法求算术平方根
import math
a = int(input())
x = 1
while math.fabs(math.sqrt(a) - x) >= 1e-6:
x = (x + a / x) / 2
print("{0}的算术平方根为:{1}".format(a, x))
韩信点兵
ls = []
for i in range(0, 1001):
if i % 7 == 2 and i % 5 == 3 and i % 3 == 2:
ls.append(i)
print("0-1000中被3除余2,被5除余3,被7除余2的数有:")
for i in ls:
print(i, end=' ')
小球反弹
h = 100
i = 0
s = 0
while i < 10:
s += h*2
i += 1
h /= 2
print(s-100, h)
猴子吃桃
p = 1
print("第8天的桃子数为:{0}".format(p))
for i in range(7, 0, -1):
print("第{0}天的桃子数为:{1}".format(i, (p+1)*2))
p = (p+1)*2
输出 1 到 100 之间的所有素数,每行输出 5 个
cnt = 0
for n in range(2, 101):
flag = 1
for m in range(2, n):
if n % m == 0:
flag = 0
break
if flag == 1:
cnt += 1
print("{0:<3d}".format(n), end='')
if cnt % 5 == 0:
print()
从键盘输入两个正整数,计算输出其最大公约数。要求,对正确的输入,可得
到正确结果,对错误的输入,使用 try-except 结构给出输入错误提示。
try:
a = int(input("请输入第一个正整数:"))
b = int(input("请输入第二个正整数:"))
if a <= 0 or b <= 0:
raise ValueError("请输入正整数!")
else:
while b != 0:
a, b = b, a % b
print(a)
except ValueError as e:
print(e)
输出ASCII码值
s = input()
ls = []
for i in range(0, len(s)):
ls.append(ord(s[i]))
print(ls)
文本文件 data.txt 中保存一批实数,读文件,统计数据个数、最大数、最小数
和平均值。
ls1 = []
ls2 = []
with open("data.txt", 'r') as f:
lines = f.readlines()
data = [(line.strip()) for line in lines]
for i in data:
ls1.append(list(i.split(' ')))
for j in ls1:
for k in j:
if k != '':
ls2.append(int(k))
print("数据个数:", len(ls2))
print("最大值:", max(ls2))
print("最小值:", min(ls2))
f.close()
从键盘中输入一批数据,以-9999 结束,统计数据个数、平均值,最大值、最
小值,并将这些数据和统计结果写入文件 result.txt
data = []
while 1:
nums = input("请输入一个实数,或者输入-9999结束输入: ")
if nums == '-9999':
break
data.append(float(nums))
count = len(data)
max_value = max(data)
min_value = min(data)
average = sum(data) / count
with open('result.txt', 'w', encoding='utf-8') as f:
for a in data:
f.write(str(a) + '\n') # 必须是以字符串的形式写入
f.write("统计结果" + '\n')
f.write("数据个数:{0}".format(count) + '\n')
f.write("最大值:{0}".format(max_value) + '\n')
f.write("最小值:{0}".format(min_value) + '\n')
f.write("平均值:{0}".format(average) + '\n')
类和对象
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
class Student(Person):
def __init__(self, name, age, score):
super().__init__(name, age)
self.score = score
def get_MaxScore(self):
return max(self.score)
s1 = Student('小明', 18, [93, 68, 76])
print("姓名:", s1.get_name())
print("年龄:", s1.get_age())
print("最高分数:", s1.get_MaxScore())
class Cacul_Score():
def __init__(self, python, c, sql):
self.python = python
self.c = c
self.sql = sql
def get_sum(self):
sum_score = self.python + self.c + self.sql
avrg_score = sum_score / 3
print("总成绩为:{0},平均成绩为:{1}".format(sum_score, avrg_score))
s1 = Cacul_Score(98, 88, 84)
s1.get_sum()
class Student():
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def get_name(self):
return str(self.name)
def get_age(self):
return int(self.age)
def get_course(self):
return max(self.score)
wh = Student('王红',20,[69,88,100])
zk = Student('张凯',19,[99,86,98])
print(wh.get_course())
print(zk.get_course())