Warm tip: This article is reproduced from serverfault.com, please click

python-如何通过调用值来对变量进行条件处理?

(python - 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谢谢阅读。问候。

Questioner
Ulises Antonio Chávez
Viewed
0
ltaljuk 2020-11-30 06:59:18

你快完成了!只需根据需要修改{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