【问题标题】:How to condition a variable by calling the value?如何通过调用值来条件变量?
【发布时间】:2020-11-29 22:45:04
【问题描述】:

我有一个疑问。以前我用我学到的所有东西制作了我的第一个 Python 程序,它是关于自动售货机系统的,但其中一个主要问题是它在调节时过于冗余并最终延长了代码。所以他们向我解释说,我应该定义函数并在它们没有实现的情况下返回。

但我的问题是,如何通过条件化来调用变量的值,特别是数字?

例子:

# -*- coding: utf-8 -*-


def select_ware(wares):
    print(' '.join(wares))
    while True:
        selected = input("Elige un código: ")
        if selected in wares:
            print(f'El precio es de: {wares[selected]}\n')
            break
        else:
            print("El código no existe, introduce un código válido")
    return selected

def pay_ware(wares, selected):
    money_needed = wares[selected]
    money_paid = 0
    while money_paid < money_needed:
        while True:
            try:
                money_current = float(input("Introduce tu moneda: "))
                break
            except ValueError:
                print('Please enter a number.')

        money_paid += money_current
        print(f'Paid ${money_paid}/${money_needed}')

        if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
            print(f'Su cambio es ${money_paid-money_needed}')        
        
    return money_paid, money_needed

def main():
    wares = {'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11}

    selected_ware = select_ware(wares)
    pay_ware(wares, selected_ware)


if __name__ == "__main__":
    main()

问题是这样的:

if money_paid>{select_ware}: #This is the part where I want to substitute the value to call the variable.
    print(f'Su cambio es ${money_paid-money_needed}')  

如何实现它以避免为每个值(即'A1': 6, 'A2': 7.5, 'A3': 8, 'A4': 10, 'A5': 11 的值)制作长条件? 谢谢阅读。问候。

【问题讨论】:

    标签: python windows function variables redundancy


    【解决方案1】:

    你快完成了!只需根据需要的钱修改 {select where}。您还可以修改 Try Exception 语句以避免在当前货币为浮点数之前停止程序:

    def pay_ware(wares, selected):
        money_needed = wares[selected]
        money_paid = 0
        valid_money_current = False # para chequear que el pago sea con monedas
        while money_paid < money_needed:
            while not valid_money_current:
                    money_current = float(input("Introduce tu dinero: "))
                    if type(money_current) is float:
                        valid_money_current = True # el pago es valido
                    else:
                        print('Please enter a number.')
    
            money_paid += money_current
            print(f'Paid ${money_paid}/${money_needed}')
    
            if money_paid > money_needed: #This is the part where I want to substitute the value to call the variable.
                print(f'Su cambio es ${money_paid-money_needed}')        
            
        return money_paid, money_needed
    

    【讨论】:

    • 哦,我现在明白了,我没有看到细节>_
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2023-03-24
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多