变量未在不同功能中定义

时间:2019-05-14 20:06:05

标签: python function

每当我输入一个值时,都会被告知未定义变量。我很确定这是因为两个功能是分开的,但是我不知道如何将它们精确地结合在一起。用户应该只为gr输入R,S或U,为gal输入大于零的数字。

例如,如果我输入S,则会得到:NameError:未定义名称'S'

 #gas1.py

def main():
    gr=eval(input("\nEnter the gas grade. R for Regular, S for Special, U for Super: "))

    while (gr!=R or gr!=S or gr!=U):
        gr=eval(input("\nGas Grade must be R, S, or U. Enter the gas grade. R for Regular, S for Special, U for Super: "))
    gal=eval(input("Enter the number of gallons: "))
    while (gal<0):
        gal=eval(input("\nNumber of gallons must be greater than zero. Enter the number of gallons: "))


def gasCost(gr, gal):
    if gr==R:
        cost=2.49*gal
        print("You purchased", gal, "gallons of Regular gas at $2.49 per gallon.")
        print("Your payment is $", format(cost, "0.2f"))
    elif gr==S:
        cost=2.79*gal
        print("You purchased", gal, "gallons of Special gas at $2.79 per gallon.")
        print("Your payment is $", format(cost, "0.2f"))
    else:
        cost=2.99*gal
        print("You purchased", gal, "gallons of Super gas at $2.99 per gallon.")
        print("Your payment is $", format(cost, "0.2f"))




main()

1 个答案:

答案 0 :(得分:0)

气体等级是字符吗?如果是这样,则需要删除eval()。

代码应该看起来像这样:

    gr=input("\nEnter the gas grade. R for Regular, S for Special, U for Super: ")
    while (gr!='R' or gr!='S' or gr!='U'):
        gr=input("\nGas Grade must be R, S, or U. Enter the gas grade. R for Regular, S for Special, U for Super: ")
    gal=eval(input("Enter the number of gallons: "))
    while (gal<0):
        gal=eval(input("\nNumber of gallons must be greater than zero. Enter the number of gallons: "))