为什么我的代码继续使用else语句?

时间:2019-07-03 03:32:59

标签: python dictionary if-statement random

因此,我正在尝试为我的朋友们和我为我们玩的笔和纸RPG开发一个骰子滚轮应用。骰子上的数字与某个结果相关,因此我制作了一个字典来记录这些结果,并编写了if语句将这些结果指出。问题是,我的程序无法识别某些数量的模具的值,而仅输出“ else”语句。

我尝试使用大于和小于语句的范围(在'and'逻辑语句中进行绑定),并且得出了一个简单的range语句。我的代码说没有错,它只输出数字3-9的“ else”语句。

sroll=dict()
sroll[1]="Blank"
sroll[3]="Opp"
sroll[6]="Succ/Str"
sroll[8]="Succ"
sroll[10]="Succ/Opp"
sroll[11]="Crit/Str"
sroll[12]="Crit"



numsdie=int(input("Now how many skill die would you like to cast?"))

def sroller():
    if diecasts<=2:
        print(sroll[1])
    elif 3 < diecasts < 5:
        print(sroll[3])
    elif 6 < diecasts < 7:
        print(sroll[6])
    elif 8 < diecasts < 9:
        print(sroll[8])
    elif diecasts==10:
        print(sroll[10])
    elif diecasts==11:
        print(sroll[11])
    else:
        print(sroll[12])

for _ in range (numsdie):
    diecasts=int(randint(1,12))
    print(diecasts)
    sroller()

没有错误消息弹出,但是如果randint给我的数字小于2,则将输出预期的答案。但是,当randint给定3,9之间的任何数字时,程序将输出“ Crit”,只有在randint输出12的情况下才应如此。当randint输出1,2,10,11,12时。他们给出正确的陈述。在压缩代码或解决问题方面将提供任何帮助。

3 个答案:

答案 0 :(得分:2)

6 < diecasts < 7diecasts为6.1或6.9时为true,但在恰好为6或7时为true。您可能想要<=

在旁注中,3 < diecasts < 5确实包含4的大小写,因此您应该在print(sroll[3])为4时看到它。

答案 1 :(得分:0)

显然,这是更冗长的解决方案,我可能会说这不是最正确的答案,但它的功能强大并且可能更易于阅读,因此我觉得值得添加。

from random import randint

sroll=dict()
sroll[1]="Blank"
sroll[3]="Opp"
sroll[6]="Succ/Str"
sroll[8]="Succ"
sroll[10]="Succ/Opp"
sroll[11]="Crit/Str"
sroll[12]="Crit"

numsdie=int(input("Now how many skill die would you like to cast?"))

def sroller():
    if diecasts == 1 or diecasts == 2:
        print(sroll[1])
    if diecasts == 3 or diecasts == 4 or diecasts == 5:
        print(sroll[3])
    if diecasts == 6 or diecasts == 7:
        print(sroll[6])
    if diecasts == 8 or diecasts == 9:
        print(sroll[8])
    if diecasts == 10:
        print(sroll[10])
    if diecasts == 11:
        print(sroll[11])
    if diecasts == 12:
        print(sroll[12])

for _ in range (numsdie):
    diecasts=int(randint(1,12))
    print(diecasts)
    sroller()

答案 2 :(得分:-3)

也许可以像下面那样更改程序。

def sroller(diecasts):
    if diecasts<=2:
        print(sroll[1])
    elif 3 < diecasts < 5:
        print(sroll[3])
    elif 6 < diecasts < 7:
        print(sroll[6])
    elif 8 < diecasts < 9:
        print(sroll[8])
    elif diecasts==10:
        print(sroll[10])
    elif diecasts==11:
        print(sroll[11])
    else:
        print(sroll[12])

for _ in range (numsdie):
    diecasts=int(randint(1,12))
    print(diecasts)
    sroller(diecasts)