如果数字小于零,如何将数字设置为零

时间:2018-10-15 10:16:01

标签: python

我正在为掷骰子游戏编写代码。我想做到这一点,以使球员的分数永远不会低于零。有什么想法吗?

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
if d_1 <= 0:
    print ("test")

if d_2 <= 0:
    d_2.append(0)
print (play1, "Your total points is",d_1)
print (play2, "Your total points is",d_2)

2 个答案:

答案 0 :(得分:0)

因为d_2是一个整数而不是一个列表,所以不要这样做(这会导致错误,因为您不能追加到整数);

if d_2 <= 0:
    d_2.append(0)

您应该像这样;

if d_2 < 0:
    d_2 = 0

答案 1 :(得分:0)

如果一次重复if/else,则可以设置字典并处理所有字典。要处理小于0的值,只需在打印odd操纵得分

之前设置一个条件
dicta = {play1: d_1, play2: d_2}

for k, v  in dicta.items():
    if not v % 2:
        print(k, "your total points are", v+10)
    else:
        if v - 5 < 0:
            print(k, "your total points are", 0)
        else:
            print(k, "your total points are", v-5)