Python 跳过规则

Python Skipping Rule

我正在为一个学校项目制作这段代码,每当它输入偶数时,它应该检查该数字是否在列表中,然后将其加 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,)

您应该使用 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)没有将结果赋值

这是经过一些修改的清理版本,我建议在此处使用 random.choice 并且只 select 从一系列数字中随机生成一个数字,这样您就不必随机生成一个新的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