【问题标题】:How do I pass user input as a parameter in a function?如何在函数中将用户输入作为参数传递?
【发布时间】:2021-12-24 04:37:07
【问题描述】:

我正在尝试编写一个程序来计算两个州之间的距离(以英里为单位)。它应该提示用户从预先确定的列表中选择一个状态。然后它应该识别状态及其对应的坐标。之后程序应输入坐标作为函数“distance_calc”的参数并生成以英里为单位的距离。我无法找到将用户输入连接到我创建的元组以及函数“distance_calc”的方法。我是 python 新手,所以任何帮助表示赞赏。

 #assign coordinates to location variable
washington_dc = (38.9072, 77.0369)
north_carolina = (35.7596, 79.0193)
florida = (27.6648, 81.5158)
hawaii = (19.8968, 155.5828)
california = (36.7783, 119.4179)
utah = (39.3210, 111.0937)
print('This Program Calculates The Distance Between States In Miles')

def distance_calc(p1, p2):
    long_1 = p1[1] * math.pi/180
    lat_1 = p1[0] * math.pi/180
    long_2 = p2[1] * math.pi/180
    lat_2 = p2[0] * math.pi/180

    dlong = long_1 - long_2
    dlat = lat_1 - lat_2
    a = math.sin(dlat / 2) ** 2 + math.cos(lat_1) * math.cos(lat_2) * (math.sin(dlong / 2) ** 2)
    c = 2 * 3950 * math.asin(math.sqrt(a))
    result = round(c)
    print(result,"miles")
    return result

【问题讨论】:

  • 欢迎来到 Stack Overflow!请以文本形式发布代码,而不是屏幕截图。 idownvotedbecau.se/imageofcode
  • 创建一个字典,将状态名称映射到相应的值。向用户询问状态,在字典中查找,然后以该状态为参数调用函数。
  • 看在上帝的份上...将您的代码粘贴到问题中的适当代码块中。在 StackOverflow 上提问时,IDE 的图片是您可能会做的最糟糕的事情之一。它们使任何想要帮助的人的工作变得更加困难,并且使用无障碍技术的人被切断了。

标签: python function parameters tuples user-input


【解决方案1】:

使用字典将州名映射到坐标

states = {
    "washington_dc": (38.9072, 77.0369),
    "north_carolina": (35.7596, 79.0193),
    "florida": (27.6648, 81.5158),
    "hawaii": (19.8968, 155.5828),
    "california": (36.7783, 119.4179),
    "utah": (39.3210, 111.0937)
}

while True:
    state1 = input("First state: ")
    if state1 in states:
        break;
    else:
        print("I don't know that state, try again")

while True:
    state2 = input("Second state: ")
    if state2 in states:
        break;
    else:
        print("I don't know that state, try again")

distance_calc(states[state1], states[state2])

【讨论】:

  • Tysm 这行得通!我一定会查看这段代码并将其添加到我的工具带中!
【解决方案2】:

您可以使用dict 进行用户输入

state_dict={1:washington_dc,2:north_carolina,3:florida,4:hawaii,5:california,6:utah}
states = ['forwashington_dc','north_carolina','florida','hawaii','california','utah']

a = [ print("Choose id {} for {}".format(states.index(st)+1,st)) for st in states]
p1 = int(input("Choose Desired States id at Start :"))
p2 = int(input("Choose Desired States id at Start :"))

print("You Have Choosen Starting Point :",states[p1])
print("You Have Choosen End Point :",states[p2])

distance_calc(state_dict[p1], state_dict[p2])

【讨论】:

    猜你喜欢
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2016-03-12
    • 2021-07-16
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多