Python跳过规则

2024-09-30 10:32:21 发布

您现在位置: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

相关问题 更多 >

    热门问题