本文最后更新于 1169 天前,其中的信息可能已经有所发展或是发生改变。
实例:[1]
输出斐波那契数列
a, b = 0, 1
for _ in range(20):
a, b = b, a + b
print(a)
寻找水仙花数
for num in range(100, 1000):
low = num % 10
mid = num // 10 % 10
high = num // 100
if num == low ** 3 + mid ** 3 + high ** 3:
print(num)
正整数的反转
num = int(input('num = '))
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
print(reversed_num)
Craps游戏
from random import randint
money = 1000
while money > 0:
print(f'你的总资产为: {money}元')
go_on = False
# 下注金额必须大于0小于等于玩家总资产
while True:
debt = int(input('请下注: '))
if 0 < debt <= money:
break
# 第一次摇色子
# 用1到6均匀分布的随机数模拟摇色子得到的点数
first = randint(1, 6) + randint(1, 6)
print(f'\n玩家摇出了{first}点')
if first == 7 or first == 11:
print('玩家胜!\n')
money += debt
elif first == 2 or first == 3 or first == 12:
print('庄家胜!\n')
money -= debt
else:
go_on = True
# 第一次摇色子没有分出胜负游戏继续
while go_on:
go_on = False
current = randint(1, 6) + randint(1, 6)
print(f'玩家摇出了{current}点')
if current == 7:
print('庄家胜!\n')
money -= debt
elif current == first:
print('玩家胜!\n')
money += debt
else:
go_on = True
print('你破产了, 游戏结束!')