TypeError:无法解压缩不可编辑的非类型对象:找不到我的数据转换为“无类型”的位置

2024-05-26 11:08:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始学习代码,我开始学习python 我想问一些我在jetbrains学院练习的事情

当我编写如下代码时, 我明白了 TypeError:无法解压缩不可编辑的非类型对象

我知道关于这个打字错误有几个问题, 但我无法理解这些评论, 我也不知道怎么了。。。。 你们中的一些人介意看看这个,告诉我为什么我会出错。。。? 如果有什么尴尬的事情,请多加评论

# declaring the current status of the coffee machine
def status(water, milk, beans, cups, money):
    print('The Coffee machine has:')
    print(water, 'of water')
    print(milk, 'of milk')
    print(beans, 'of coffee beans')
    print(cups, 'of disposable cups')
    print(money, 'of money')


# espresso
def espresso(water, beans, money):
    water -= 250
    beans -= 16
    money += 4
    return water, beans, money

# latte
def latte(water, milk, beans, money):
    water -= 350
    milk -= 75
    beans -= 20
    money += 7
    return water, milk, beans, money

# cappuccino
def cappuccino(water, milk, beans, money):
    water -= 200
    milk -= 100
    beans -= 12
    money += 6
    return water, milk, beans, money

# buy
def buying(water, milk, beans, money):
    coffee = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ')
    if coffee == 1:
        water, beans, money = espresso(water,beans, money)
        return water, milk, beans, money
    elif coffee == 2:
        water, milk, beans, money = latte(water, milk, beans, money)
        return water, milk, beans, money
    elif coffee == 3:
        water, milk, beans, money = cappuccino(water, milk, beans, money)
        return water, milk, beans, money

status(water, milk, beans, cups, money)
water, milk, beans, money = buying(water, milk, beans, money)
status(water, milk, beans, cups, money)

Tags: of代码returndefstatuscoffeeprintespresso
2条回答

您需要将用户输入转换为int

coffee = int(input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: '))

检查整数时,input()函数返回一个字符串

这样做-

# buy
def buying(water, milk, beans, money):
    coffee = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ')
    # Convert string to integer
    # keep in mind it will throw ValueError if input was not an integer
    coffee = int(coffee)

您也可以将if语句更改为

# Notice the quotes
if coffee == '1':

此外,最好在函数结束时返回。这样,即使输入错误,也不会得到TypeError(例如,当用户输入4时)

def buying(water, milk, beans, money):
    coffee = input('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino: ')
    
    if coffee == '1':
        water, beans, money = espresso(water,beans, money)
    elif coffee == '2':
        water, milk, beans, money = latte(water, milk, beans, money)
    elif coffee == '3':
        water, milk, beans, money = cappuccino(water, milk, beans, money)

    return water, milk, beans, money

相关问题 更多 >