我怎么知道我程序的逻辑是否正确?

时间:2019-04-15 18:12:17

标签: python python-3.x python-2.7 ipython

我的作业是写一个计算出租车费的程序。但是,出租车的基本费用为2.00英镑,前五英里中的每英里收费2.00英镑,此后每英里为1.00英镑。老师给了我们一个提示,说我们可以编写将票价作为函数计算的部分

这就是我所做的... 没有错误,但是唯一的问题是输入任何距离时我的程序都无法工作

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英里的输出为“错误”,但是我的程序没有输出

1 个答案:

答案 0 :(得分:3)

功能distance_into_money应该在逻辑语句之外定义。首先,将逻辑应用于该功能会更好。

让我们也重新整理您的逻辑:

  1. 5英里以下,票价为2美元(基本)+ 2美元/英里。
  2. 5英里以上的票价为$ 2(基本)+ $ 2 /英里* 5(5英里)+ $ 1 /英里(5英里以上的每英里)。将所有内容重新整理到您的代码中,我们得到
# 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).