我希望能够将距离列表从英里更改为公里,其中英里列表用以下代码位获得:
input_string = input("Enter a list of distances, separated by spaces").strip()
要将输入列表更改为整数列表,我使用:
distances = input_string.split()
print("This is what you entered: ")
for distance in distances:
print(distance)
def str2int(word):
"""Converts the list of string of miles into a list of integers of miles"""
integer = int(word)
if int(word):
return integer
else:
sys.exit("Please try again and enter a list of integers.")
def validate_all(distances):
"""
Checks if all the inputs are integers. If not all are integers, sys.exit
without converting any of the distances and ask to try again.
"""
true_list = []
for distance in distances:
if str2int(distance):
true_list.append(distance)
if len(distances) == len(true_list):
return True
else:
return False
print("And now, we are going to convert the first one to kilometers:")
miles = distances[0]
if validate_all:
# now, the calculation and display
kms = miles_int * KMPERMILE
print("The first distance you entered, in kilometers:", kms)
for i in range(1, len(distances), 1):
miles_int = str2int(distances[i])
kms = miles_int * KMPERMILE
print("The next distance you entered in kilometres:", kms)
但是,当我试图检查字符串列表中的所有元素是否都可以更改为整数(使用validate_all(word))并具有如下内容时
12 23 apples banana 5
作为我的输入,程序崩溃,说在
str2int(word)
-> if int(word):
而不是我拿到系统出口
有人能帮我调试一下这个吗?
目前没有回答
相关问题 更多 >
编程相关推荐