- 求两个数的最小公倍数
# 定义函数
def lcm(x, y):
# 获取最大的数
if x > y:
greater = x
else:
greater = y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1
return lcm
# 获取用户输入
num1 = int(input("输入第一个数字: "))
num2 = int(input("输入第二个数字: "))
print( num1,"和", num2,"的最小公倍数为", lcm(num1, num2))
结果:
输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最小公倍数为 216
2.逆转一个字符串
def test(str):
print(str[::-1])
oldString = input()
test(oldString)
结果:
3.九九乘法表
for i in range(1, 10):
for j in range(1,i+1):
print('%s*%s=%s'%(i,j,i*j), end=" ")
print(" ")
结果:
3. 斐波那契额数列
# 获取用户输入数据
nterms = int(input("你需要几项?"))
# 第一和第二项
n1 = 0
n2 = 1
count = 2
# 判断输入的值是否合法
if nterms <= 0:
print("请输入一个正整数。")
elif nterms == 1:
print("斐波那契数列:")
print(n1)
else:
print("斐波那契数列:")
print(n1,",",n2,end=" , ")
while count < nterms:
nth = n1 + n2
print(nth,end=" , ")
# 更新值
n1 = n2
n2 = nth
count += 1
结果:
方法2:
a, b = 0, 1
while b < 10:
print(b)
a,b = b,a+b
结果:
1
1
2
3
5
8