使用if else语句在python中分配变量

时间:2016-01-22 00:17:22

标签: python python-3.x if-statement

我正在尝试制作一个程序,告诉您如何订购特定数量的块,使用if和else语句来分配变量。我的问题是如果第一个if语句之一为真,那么程序会抛出一个错误,因为我调用了一个不存在的变量。如果第一个被发现是真的,我如何让我的程序跳过其余的if / else语句?

nuggets = input("How many nuggets do you need? ")

nuggets = int(nuggets)

nuggets20 = nuggets % 20


if nuggets20 == 0:
    n20 = True

else: 
     nuggets10 = nuggets20 % 10

if nuggets10 == 0:
    print(nuggets10)

else: 
    nuggets6 = nuggets10 % 6

if nuggets6 == 0:
    print(nuggets6)

else:
    nuggets4 = nuggets6 % 4



if n20 == True:
    print("nuggets")

1 个答案:

答案 0 :(得分:2)

这是一种可怕的做法,但你可以使用厄运方法的箭头。

if nuggets20 == 0:
    n20 = True

else: 
     nuggets10 = nuggets20 % 10

    if nuggets10 == 0:
        print(nuggets10)

    else: 
        nuggets6 = nuggets10 % 6

        if nuggets6 == 0:
            print(nuggets6)

        else:
            nuggets4 = nuggets6 % 4



if n20 == True:
    print("nuggets")
那说,这有点傻不是吗?您基本上是在实施变更制造者,因此请使用已存在的数千种方法中的一种,这些方法都不使用可能存在或不存在的随机变量。我最喜欢的是字典。

result = {"20-piece": 0, "10-piece": 0,
          "6-piece": 0, "4-piece": 0}

total_nuggets = nuggets = 128

for mod_num, key in [(20, "20-piece"), (10, "10-piece"),
                     (6, "6-piece"), (4, "4-piece")]:
    result[key], nuggets = divmod(nuggets, mod_num)

if nuggets != 0:
    # you have single nuggets!

此示例离开:

results == {'10-piece': 0, '4-piece': 0, '6-piece': 1, '20-piece': 6}