首页 > 解决方案 > 如何使函数在条件下使用默认参数

问题描述

在这段代码中,如果用户决定使用默认值并单击回车,我想让函数使用默认参数,这会导致输入为空字符串。

但是,就我而言;它只是使用用作参数的空字符串运行代码。

arc = ArcGIS()

def mapMaker(country, zoom = 4, location = "~/Desktop/", name = "Untitled"):
    loc = arc.geocode(country)
    countryLat = loc.latitude
    countryLon = loc.longitude
    map = folium.Map(location=[countryLat, countryLon], zoom_start=zoom, min_zoom=2)
    map.save("%s.html" % location + name)

mapZoom = input("Choose Your Map's Starting Zoom:(Default = 4) ")
mapLoc = input("Choose Where Your Map File Will Be Created:(Default = ~/Desktop) ")
mapName = input("Choose Your Map's Name:(Default = Untitled) ")
mapMaker(userin, zoom = mapZoom, location = mapLoc, name = mapName )

PS:我知道之前有人问过类似的问题,但我无法使用此代码使其工作,因为此函数有更多参数。

标签: pythonpython-3.xfunction

解决方案


我会通过使用字典而不是参数来解决这个问题,这样,您可以在旅途中将参数设置为默认值。它看起来像这样:

def mapMaker(myDict):
    #access the arguments via mydict['your_argument']


myDict = {}
myDict['mapZoom'] = int(input("Choose Your Map's Starting Zoom:(Default = 4) ") or 4)})
myDict['mapLoc'] = str(input("Choose Where Your Map File Will Be Created:(Default = ~/Desktop) ") or '~/Desktop')
myDict['mapName'] = str(input("Choose Your Map's Name:(Default = Untitled) ") or 'Untitled')
mapMaker(myDict)

推荐阅读