gpt4 book ai didi

python - Python 中的基本轮盘模拟器(仅限红/黑)

转载 作者:行者123 更新时间:2023-12-01 05:37:26 27 4
gpt4 key购买 nike

我正在用 python 编写一个非常基本的轮盘模拟器。目前,我只专注于红/黑投注(基本上与投注正面或反面相同,使用硬币)。

我的代码有各种问题。请原谅我对语言的基本了解。

import random

# Defines initial amounts of money and losses
money = 50
losses = 0


# Asks user how much to bet
def roulette_sim():
print "How much do you want to bet?"
bet = raw_input("> ")
if bet > money:
bet_too_much()
else:
red_or_black()


# Prevents one from betting more money than one has
def bet_too_much():
print "You do not have all that money. Please bet again."
raw_input("Press ENTER to continue> ")
roulette_sim()

# Asks user to select red or black, starts the sim, modifies money/losses
def red_or_black():
print "OK, you bet %r" % (bet)
print "Red or black?"
answer = raw_input("> ")
number = random.randint(1, 2)
if number == 1 and answer == "red":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
elif number == 2 and answer == "black":
print "You win!"
money += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()
else:
print "You lost!"
money -= bet
losses += bet
print "You now have %r money" % (money)
print "Your losses are %r" % (losses)
replay()

# Asks user whether he/she wants to play again
def replay():
print "Do you want to play again?"
play_again = raw_input("y/n> ")
if play_again == "y":
roulette_sim()
else:
print "OK, bye loser!"


roulette_sim()

到目前为止的第一个问题:bet_too_much 函数不起作用。无论我输入多少金额,程序都会指出太多(即:“赌注”总是大于“金钱”)。为什么?

到目前为止的第二个问题:当我想使用以下方法在“金钱”中添加/减去“赌注”时: 钱+=赌注python 将此视为对 int 与字符串求和(至少我认为是这样),而不是对两个变量求和。这是为什么?

如有任何帮助,我们将不胜感激。

谢谢

最佳答案

这两种情况都会发生,因为 Python 不进行隐式转换。你必须明确地告诉它你想要某个东西是一个整数,它不会为你做这件事。因此,对于第一期:

bet = raw_input("> ") 
if bet > money:
...

必须是

bet = raw_input("> ")
bet = int(bet)
if bet > money:
...

因为您不想将字符串与整数进行比较(您可以,但要使用您现在得到的结果)。

对于第二个,你也必须明确:

money += int(bet)

(当然,如果您已经将 bet 转换为 int,那就没问题了)。

Javascript 因执行这种隐式转换而臭名昭著,因此,如果您碰巧熟悉这种语言或类似的语言,请忘记它并明确您正在使用的类型。总的来说,哪个更安全。

关于python - Python 中的基本轮盘模拟器(仅限红/黑),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18588825/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com