简体   繁体   English

如何在函数中将用户输入作为参数传递?

[英]How do I pass user input as a parameter in a function?

I'm trying to write a program that finds the distance in miles between two states.我正在尝试编写一个程序来查找两个州之间以英里为单位的距离。 It should prompt a user to choose a state from a predetermined list.它应该提示用户从预定列表中选择一个状态。 Then it should identify the state and its corresponding coordinates.然后它应该识别状态及其对应的坐标。 Afterwards the program should enter the coordinates as parameters of the function "distance_calc" and generate the distance in miles.然后程序应该输入坐标作为函数“distance_calc”的参数并生成以英里为单位的距离。 I'm having trouble finding a way to connect the user input, to the tuples I've created and those to the function "distance_calc".我无法找到将用户输入连接到我创建的元组以及那些连接到函数“distance_calc”的方法。 I'm new to python so any help is appreciated.我是 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

Use a dictionary to map state names to coordinates使用字典将州名映射到坐标

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])

You can use dict for user input您可以使用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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM