如何缩短或清理此 python 代码?

我有一个家庭作业,要编写一个程序,该程序将高速公路编号作为输入,并输出高速公路是主要还是辅助,走向东/西,北/南,如果是辅助,它服务的主要高速公路是什么。这是我的代码,它给了我满分,但我是初学者,必须有更短的方法来编写它。有人介意清理一下吗?


highway_number = int(input())


if highway_number >= 1 and highway_number <= 99:

    prim = 'is primary,'

    if (highway_number % 2) == 0:

        print('The', highway_number, prim, 'going east/west.')

    else:

        print('The', highway_number, prim, 'going north/south.')

elif highway_number >= 100 and highway_number <= 999:

    aux = 'is auxiliary,'

    if (highway_number % 2) == 0:

        print('The', highway_number, aux, 'serving the %d, going east/west.' % (highway_number%100))

    else:

        print('The', highway_number, aux, 'serving the %d, going north/south.' % (highway_number%100))

else:

    print(highway_number, 'is not a valid interstate highway number.')

这里有 290 个输出:


The 290 is auxiliary, serving the 90, going east/west.


鸿蒙传说
浏览 116回答 1
1回答

繁华开满天机

用于1) 链式比较2) f弦3) 利用 0/1 的布尔值的内联 if 语句使代码更短highway_number = int(input())if 1 <= highway_number <= 99:&nbsp; &nbsp; direction = 'east/west' if highway_number % 2 else 'north/south'&nbsp; &nbsp; print(f'The {highway_number} is primary, going {direction}')elif 100 <= highway_number <= 999:&nbsp; &nbsp; direction = 'north/south' if highway_number % 2 else 'east/west'&nbsp; &nbsp; print(f'The {highway_number} is auxiliary, serving the {highway_number%100}, going {direction}')else:&nbsp; &nbsp; print(highway_number, 'is not a valid interstate highway number.')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python