如何计算变量之间的数字

时间:2018-11-14 15:28:36

标签: python

我需要编写这段代码,但是我无法弄清楚如何计算超出人所能达到的速度的英里数。

speed = int(input("How fast where they going? (in mph) "))
limit = int(input("What is the speed limit? "))

if speed > limit:
    print("Illegal Speed!")
    if speed > 90:
        fine = 250
        for i in speed:
            fine = fine + 5
        print("Their fine is $", fine)
    else:
        fine = 50
        for i in speed:
            fine = fine + 5
        print("Their fine is $", fine)

if speed <= limit:
    print("Legal Speed")

2 个答案:

答案 0 :(得分:2)

考虑到查尔斯(Charles)关于您打算在速度限制上每英里每小时增加5的想法是正确的,我相信此解决方案会更干净:

speed = int(input("How fast where they going? (in mph) "))
limit = int(input("What is the speed limit? "))

if speed > limit:

    print("Illegal Speed!")

    if speed > 90:
        fine = 250
    else:
        fine = 50

    fine += (speed - limit) * 5
    print("Their fine is $", fine)

else:

    print("Legal Speed")

由于两种情况下的精细计算和打印均相同,因此将其置于“公共区域”并使用if / else仅设置“精细”初始值会更容易。

答案 1 :(得分:1)

如果您想在速度限制上每英里每小时增加5,则只需(speed-limit)*5

您的代码将导致:

speed = int(input("How fast where they going? (in mph) "))
limit = int(input("What is the speed limit? "))

if speed > limit:
    print("Illegal Speed!")
    if speed > 90:
        fine = 250
        adder = (speed-limit) * 5
    else:
        fine = 50
        adder = (speed-limit) * 5

    print("Their fine is $", (fine+adder))
if speed <= limit:
    print("Legal Speed")