我正在使用小型铁路网络对图数据结构进行一些练习。一开始,我要求用户提供一个起始目的地和一个结束目的地。用户输入必须是目标列表中的值。到目前为止我写的:
a = 0
b = 0
while a == 0:
start_point = input("nWhat is your starting location?n").title()
if start_point in valid_destinations:
print("That is a valid starting location.")
a = 1
else:
print("Please choose one of the cities in our network.")
continue
while b == 0:
end_point = input("nWhat is your destinationn").title()
if end_point in valid_destinations:
print("That is a valid destination.")
b = 1
else:
print("Please choose one of the cities in our network.")
continue
因为它们是单独的问题,这是否意味着必须有单独的 while 循环?我尝试在一个中同时执行它们,但我无法让验证功能正常工作。它的功能如上面写的一样,但我觉得它可以更有效率,重复更少。
您可以在一个 while 循环中编写这两个问题,您只需稍微更改一下检查值的方式: 它可能类似于下面的代码,您首先检查变量是否具有默认值(在这种情况下,用户应编写其输入(,然后检查输入是否有效。
a, b = None, None # You could also use 0
while a is None or b is None:
if a is None: # a == 0
a = input('write start location: ').title()
if a not in valid_destinations:
a = None
print('Choose a valid start location.')
continue
if b is None: # b == 0
b = input('write destination: ').title()
if b not in valid_destinations:
b = None
print('Choose a valid destination.')
while 循环中的条件使得没有不必要的重复,并且在两个输入都有效时停止。