这就是我所做的... 没有错误,但是唯一的问题是输入任何距离时我的程序都无法工作
user_fare = int(input('Please enter the distance '))
if user_fare == 0:
print('2')
elif user_fare > 0 and user_fare < 5:
def distance_into_money(fare):
return ((user_fare*2)+2)
print(distance_into_money)
elif user_fare > 5:
def distance_into_money(fare):
return ((user_fare*2)+1)
print(distance_into_money)
else:
print('Error')
我希望1英里的输出为“ 4.00英镑”,而6英里的输出为“ 13.00英镑”,-1英里的输出为“错误”,但是我的程序没有输出
答案 0 :(得分:3)
功能distance_into_money应该在逻辑语句之外定义。首先,将逻辑应用于该功能会更好。
让我们也重新整理您的逻辑:
# Defining our function first allows us to use it later.
# None of the code in the function is executed until you call the function later
def distance_into_money(dist):
if 0 <= dist <= 5: # Python supports logical statements like this
return 2 + (dist*2)
if dist > 5:
return 2 + (2*5) + 1*(dist-5)
# Again, this is $2 base + $2/mil * 5 mil + $1/mi * (number of miles over 5 miles)
return -1 # Indicates there was an error: The dist was not in the acceptable bounds
users_distance = int(input("Please enter the distance "))
users_fare = distance_into_money(users_distance)
if users_fare == -1: # There was an error
print("Error")
else: #There was not an error
print("The user's fare is ${}".format(users_fare))
# The str.format method replaces the {} with its argument (which is the user's fare in this case).