皮洪跳绳

2024-04-25 22:09:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个学校项目编写这个代码,当它输入一个偶数时,它应该检查这个数字是否在列表中,然后加上10。相反,它只是跳过+10位,而是从中减去5。代码如下:

import random

print("Lets Play")
play1 = input("Player 1 name?")
play2 = input("Player 2 name?")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")

diceNumber = float(random.randint(2,12))
diceNumber2 = float(random.randint(2,12))
diceNumber3 = random.randint(2,12)
diceNumber4 = random.randint(2,12)
diceNumber5 = random.randint(2,12)
diceNumber6 = random.randint(2,12)
diceNumber7 = random.randint(2,12)
diceNumber8 = random.randint(2,12)
diceNumber9 = random.randint(2,12)
diceNumber0 = random.randint(2,12)

print(play1, "Your number is...")
print(diceNumber)
print(play2, "Your number is...")
print(diceNumber2)

evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]

if (diceNumber) == (evennumber):
    (diceNumber01) = (diceNumber) + float(10)
else:
    (diceNumber01) = (diceNumber) - float(5)

evennumber = list = [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40]
evennumber = [float(i) for i in list]

if (diceNumber2) == (evennumber):
    float(diceNumber2) + float(10)
else:
    float(diceNumber2) - float(5)

print (play1, "Your total points is",diceNumber01,)
print (play2, "Your total points is",diceNumber2,)

Tags: 代码inputyourisrandomfloatlistprint
2条回答

您应该使用in操作符来检查值是否在列表中的值中。你知道吗

更改:

if (diceNumber) == (evennumber):

收件人:

if (diceNumber) in (evennumber):

你有一些多余的和问题在这里,这里是一个简短的总结和一些变化。你知道吗

  • 只使用两个骰子,不需要创建10个
  • 骰子值为float没有明确的用途
  • 可以使用if not x % 2检查evens,如果要使用偶数列表,如图所示,唯一相关的偶数是2 through 12
  • diceNumber == evennumber正在检查一个值是否等于,如果使用正确,整个列表将是if diceNumber in evennumber
  • 此语句float(diceNumber2) + float(10)将结果赋值为nothing

这是一个经过一些修改的清理版本,我建议在这里使用random.choice,只需从一系列数字中选择一个随机数,这样就不必每次都在范围内随机生成一个新的int,结果将是相同的。你知道吗

from random import choice

print("Lets Play")
play1 = input("Player 1 name: ")
play2 = input("Player 2 name: ")
print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice")

die = list(range(2, 13))

d_1 = choice(die)
print(play1, "Your number is...\n{}".format(d_1))

d_2 = choice(die)
print(play2, "Your number is...\n{}".format(d_2))

if not d_1 % 2:
    d_1 += 10
else:
    d_1 -= 5

if not d_2 % 2:
    d_2 += 10
else:
    d_2 -= 5

print (play1, "Your total points is",d_1)
print (play2, "Your total points is",d_2)
Lets Play
Player 1 name: vash
Player 2 name: stampede
Hi vash & stampede, let's roll the dice
vash Your number is...
5
stampede Your number is...
2
vash Your total points is 0
stampede Your total points is 12

相关问题 更多 >