我有范围问题吗?

时间:2017-02-26 21:38:39

标签: python

这是我的代码,我似乎无法从输入语句的赋值中修改任何值。是否有一些我不熟悉Python的范围规则?

    days=0
    airfaire=0
    mealsPaid=0
    carRental=0
    privateMilesDriven=0
    parkingFees=0
    taxiCharges=0
    conferenceFees=0
    lodgingCharges=0

    def getInputForVariables():
        days=input("Number of days on the trip: ")
        airfaire=input("Amount of airfare, if none then enter 0: ")
        mealsPaid=input("Amount paid for meals, if none then enter 0: ")
        carRental=input("Amount of car rental fees, if none then enter 0: ")
        privateMilesDriven=input("Number of miles driven, if a private vehicle was used: ")
        parkingFees=input("Amount of parking fees, if none then enter 0: ")
        taxiCharges=input("Amount of taxi charges, if none then enter 0: ")
        conferenceFees=input("Conference or seminar registration fees, if none then enter 0: ")
        lodgingCharges=input("Lodging charges, per night: ")


    if __name__ == "__main__":
        getInputForVariables()
        print("the number of days is", days)
        print("the amount of lodginnig charges is", (lodgingCharges))

1 个答案:

答案 0 :(得分:0)

是的,您的代码存在范围问题。函数getInputForVariables仅具有在函数本身范围内定义的变量。在对函数的调用结束后,丢弃变量值。您可能想要做的是将输入存储到字典中并返回

def getInputForVariables():
    data={}
    data["days"]=input("Number of days on the trip: ")
    data["airfaire"]=input("Amount of airfare, if none then enter 0: ")
    data["mealsPaid"]=input("Amount paid for meals, if none then enter 0: ")
    data["carRental"]=input("Amount of car rental fees, if none then enter 0: ")
    data["privateMilesDriven"]=input("Number of miles driven, if a private vehicle was used: ")
    data["parkingFees"]=input("Amount of parking fees, if none then enter 0: ")
    data["taxiCharges"]=input("Amount of taxi charges, if none then enter 0: ")
    data["conferenceFees"]=input("Conference or seminar registration fees, if none then enter 0: ")
    data["lodgingCharges"]=input("Lodging charges, per night: ")
    return data
if __name__ == "__main__":
    data=getInputForVariables()
    print("the number of days is", data["days"])
    print("the amount of lodginnig charges is", (data["lodgingCharges"]

这样您就可以从返回的值中访问输入数据,并通过data["insert variable name here"]获取输入。

相关问题