我正在尝试编写一个简单的程序来测试我一直在学习的 Python 基础知识。我决定制作一个简单的开玩笑的赌博脚本,用于检查用户输入的数字与 1,100 个随机生成的数字。我想根据用户猜测的随机数与用户的随机数的接近程度将用户的赌注乘以不同的数量,但似乎无法使用 == 或 <= etc. Or at least cant work it out.
来检查范围内即,用户在数字 15 上押注 10。 如果随机数为 20,则它在用户数的 5 以内,因此将赌注乘以 25。 如果随机数是 25,则其在用户数的 10 或更少范围内,因此乘以 10 等等。
这就是我所拥有的,很想听听对此的任何建议!
if random_number == int(playernumber):
playerstake = int(playerstake) * 100
print("\nCongratulations, you hit the JACKPOT and won £" + str(playerstake) + "!!!")
#+/- 1
elif int(playernumber) == int(random_number) + 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 1:
playerstake = int(playerstake) * 50
print("\nCongratulations, you guessed within 1 of " + str(random_number) + " and won £" + str(playerstake) + "!")
#+/- 5
elif int(playernumber) == int(random_number) + 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
elif int(playernumber) == int(random_number) - 5:
playerstake = int(playerstake) * 20
print("\nCongratulations, you guessed within 5 of " + str(random_number) + " and won £" + str(playerstake) + "!")
等等等等 我知道这目前不起作用,因为我 == 随机数 + 1 所以 12 就是 13。
如果我在这里做了一些令人不悦的事情,我深表歉意,这是我尝试处理的第一个脚本,并且想看看“正确”完成此操作的潜在方法。谢谢各位的回复!
如果我理解正确,代码会简单得多:
dist = abs(guess - rand_num)
if dist == 0:
multiplier = 100
elif dist <= 1:
multiplier = 50
elif dist <= 5:
multiplier = 20
elif dist <= 10:
multiplier = 10
else:
multiplier = 0
player_stake += player_stake * multiplier
if dist == 0:
print("Congratulations you've won")
else:
print("Congratulations you guessed {0} within {1} and won ${3}".format([multiplier, rand_num, player_stake])
不要重复自己。您可以用查找表替换 if 子句。只有 3 件事,这是否更好是一个难以抉择的问题,但一般来说,如果多个条件子句中的逻辑相同,那么最好将该逻辑提取到单个实现中。查找表可让您更改用于选择的边界,而无需触及逻辑:
# assumes `diff`, `random_number` and `playerstake` defined at time of use
exact_text = f"Congratulations, you hit the JACKPOT and won £{playerstake}"
near_text = f"Congratulations, you guessed within {diff} of {random_number} and won £{playerstake}"
# lookup table: (diff, payout, text)
odds = [
(0, 100, exact_text),
(1, 50, near_text),
(5, 20, near_text)
]
playernumber = int(playernumber)
playerstake = int(playerstake)
player_diff = abs(random_number - playernumber)
for diff, payout, text in odds:
if player_diff <= diff:
playerstake *= payout
print(text)
break
else:
print(f"You were {player_diff} away from the random number")