-1

我已经制作(或更多,我正在尝试制作)一个程序来帮助我计算一些数字。我有一些级别,每个级别都会给出奖励,并且为了给出奖励,我更喜欢不插入每个金额并将它们全部加起来以获得总数。

我已经做到了,所以我写了级别编号,它将数量添加到列表中,它再次循环,我插入一个不同的数字等。

但它不会循环将数字添加到列表中。

这是我的超级非紧凑代码:

lists = []
total = 0
def moneyz():
    level=input('-> ')
    print('g') #just a testing bookmark
    print(level) #same here
    if level==1:
        print('oo') #and here
        lists.apped('150')
        total==total+150

    elif level == 2:
        lists.apped('225')
        total==total+225
        moneyz()

    elif level == 3:
        lists.apped('330')
        total==total+330
        moneyz()

    elif level == 4:
        lists.apped('500')
        total==total+500
        moneyz()

    elif level == 5:
        lists.apped('1000')
        total==total+1000
        moneyz()

    elif level == 6:
        lists.apped('1500')
        total==total+1500
        moneyz()

    elif level == 7:
        lists.apped('2250')
        total==total+2250
        moneyz()

    elif level == 8:
        lists.apped('3400')
        total==total+3400
        moneyz()

    elif level == 9:
        lists.apped('5000')
        total==total+5000
        moneyz()

    elif level == 10:
        lists.apped('15000')
        total==total+15000
        moneyz()


moneyz()
print(lists)
print(total)
4

2 回答 2

1

我可以在这段代码中看到三个错误:

  1. level是 a str,所以它永远不会等于 a int。您的if任何检查都不会得到满足,这就是您的函数不递归的原因。在调试中发现这一点的一种方法是print(repr(level))在收到输入后添加一个;您会看到它是一个类似于'1'(字符串)而不是1(整数)的值。
  2. 没有. apped()_ if_AttributeError
  3. total永远不会增加,因为你使用的是==(平等检查)运算符而不是=(赋值)运算符。

这是该程序的一个更短(工作)版本,使用一个简单的查找表代替一堆if语句:

# Rewards for levels 0 to 10.
rewards = [0, 150, 225, 330, 500, 1000, 1500, 2250, 3400, 5000, 15000]

# Running totals.
lists = []
total = 0

while True:
    # Get reward level from the user.  If not a valid reward level, stop.
    level = input('-> ')
    try:
        level_num = int(level)
    except ValueError:
        break
    if level_num not in range(len(rewards)):
        break

    # Add the reward to the lists and the total.
    reward = rewards[level_num]
    lists.append(reward)
    total += reward

# Final output.
print(lists)
print(total)
于 2019-11-03T17:14:43.063 回答
0

您正在使用level==1where level is a string 作为input()返回字符串并将其与 int 进行比较。

您应该尝试level=='1'将 level 转换为 int by level = int(input("->"))

此外,列表有append()方法而不是apped()

此外,total==total+1000不会帮助添加。它只会检查总计的值是否等于总计加 1000。您应该使用它total = total + 1000来增加价值。

这是一个修改 if 块的示例:

if level=='1':
        print('oo') #and here
        lists.append('150')
        total=total+150

希望能帮助到你。

于 2019-11-03T17:06:43.973 回答