我在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功能不起作用。无论我输入什么金额,该计划都说它太多了(即:“赌注总是大于金钱'”)。为什么呢?
到目前为止的第二个问题:当我想添加/减去' bet'来自' money'通过使用,例如: 钱+ =下注 python将此视为用字符串对int求结(至少我认为是这样)而不是求和两个变量。这是为什么?
任何帮助都将不胜感激。
由于
答案 0 :(得分:2)
这两件事都发生了,因为Python不进行隐式转换。你必须明确告诉它你想要一个整数,它不会为你做。 所以,对于第一个问题:
bet = raw_input("> ")
if bet > money:
...
必须是
bet = raw_input("> ")
bet = int(bet)
if bet > money:
...
因为您不想将字符串与整数进行比较(您可以,但结果是您现在得到的结果)。
对于第二个,你也必须明确:
money += int(bet)
(当然,如果你已经将bet
转换成了一个int,那你很好。)
Javascript因执行此隐式转换而臭名昭着,因此如果您恰好熟悉该类型或类似的语言,请忘记并明确您正在使用的类型。总的来说,这更安全。
答案 1 :(得分:0)
raw_input()
函数返回字符串值,但money
是整数。将字符串与数字进行比较总是会使Python 2的排序数字小于字符串。
将raw_input()
的结果转换为整数:
def roulette_sim():
print "How much do you want to bet?"
bet = int(raw_input("> "))
如果给定的输入不是有效数字,则可能抛出ValueError
异常;您可能希望捕获该异常并告诉用户输入一个数字:
def roulette_sim():
print "How much do you want to bet?"
while True:
try:
bet = int(raw_input("> "))
except ValueError:
print "Please enter a valid amount, a number."
else:
break
答案 2 :(得分:0)
您正在将从raw_input(“>”)获得的字符串与整数进行比较。这不会很好。 请尝试使用此功能(尚未完全测试):
def roulette_sim():
while(1):
print "How much do you want to bet?"
try:
bet = int(raw_input("> "))
break
except ValueError:
print 'You need to input a number'
if bet > money:
bet_too_much()
else:
red_or_black()
编辑:根据评论更改为“除ValueError”。我知道我对python编程的处理部分有点懒惰,但也许我不应该教给别人: - )