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

标签 python python-2.7

我正在用 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/

相关文章:

mysql - Dejavu - Python 中的音频指纹识别

python - robobrowser 处理 json 中的响应

python - 使用 Python 导入包含文本和数字数据的文件

python - 无法理解 np.where(array1==array2) 的结果

python排列,包括重复

python - 为什么 arange 和 linspace 不能产生相同的对象?

python - 当模型中的 DateField 过期时触发函数的最佳方式

python - Pynotify 搞砸了日期时间,为什么?

python - 在没有基于模型的数据库的情况下使用 Django View 和表单

python - 打印格式化的值集列表