python

python取火柴代码怎么写

小亿
107
2023-09-27 22:50:32
栏目: 编程语言

以下是一个简单的示例代码,可以用python编写取火柴的程序:

import random
def take_match(num_matches):
# 检查火柴数量是否大于零
if num_matches <= 0:
print("没有火柴可取了!")
else:
# 随机取火柴
num_taken = random.randint(1, num_matches)
print("取走了", num_taken, "根火柴。")
num_matches -= num_taken
print("还剩下", num_matches, "根火柴。")
# 测试
num_matches = 10
take_match(num_matches)

这个程序使用了random模块来生成一个随机数来表示取多少根火柴。num_matches变量表示火柴的总数量,通过调用take_match函数来取火柴,函数会打印出取火柴的数量和剩余的火柴数量。

0
看了该问题的人还看了