#Question 1
def playNovice(marbles):
import random
rand = random.randint(1,(0.5*marbles))
print('Computer takes: ', rand)
#Question 2
def userPlay(marbles):
userAmount = marbles
while userAmount > (marbles * 0.5):
userAmount = int(input("Input Number of Marbles you want to take from pile: "))
return userAmount
#Question 4
import random
marbles = random.randint(10,100)
print("Size of Marble Pile: ", marbles)
OneOrZero = random.randint(0,1)
starter = int(input("Enter a Number between 0 and 1 to decide who starts: "))
while marbles > 1:
if starter == OneOrZero:
while marbles > 1:
print("Your Turn!")
rand = userPlay(marbles)
marbles = (marbles - rand)
print(marbles, 'Marbles Remaining')
print("Computers Turn!")
rand = playNovice(marbles)
marbles = (marbles - rand)
print(marbles, 'Marbles Remaining')
elif starter != OneOrZero:
while marbles > 1:
print("Computers Turn!")
rand = playNovice(marbles)
marbles = (marbles - rand)
print(marbles, 'Marbles Remaining')
print("Your Turn!")
rand = userPlay(marbles)
marbles = (marbles - rand)
print(marbles, 'Marbles Remaining')
计算机取出弹珠后出错。很多时候我发现很难理解错误代码的含义,或者至少是如何修复它。在
^{pr2}$
如您所见,
random.randint()
只接受ints(整数)。在但是,如果使用浮点,则会产生相同的错误:
^{pr2}$这是你更新的代码
它使用math.floor来获得底部整数,因此如果
marbles
是11,我们不希望它取更高(6)的randint
。在在回溯中可以看到错误:
此函数调用的第二个值将是浮点值,而不是整数。
randint
函数只适用于整型参数。但是,异常比通常更难理解,因为randint
是引发实际异常的randrange
的包装器。在要解决这个问题,您需要使用
int
将参数强制为整数,或者以不同的方式进行计算(例如使用//
floor division操作符)。既然这看起来像是家庭作业,我就把细节留给你。在不过,稍后您可能会遇到另一个问题,即您的
playNovice
函数没有返回获取的弹珠数。你可能也要修这个!在相关问题 更多 >
编程相关推荐