[英]How can I shorten or clean up this python code?
我有一个家庭作业,要编写一个程序,该程序将高速公路编号作为输入,并输出高速公路是主要还是辅助,走向东/西,北/南,如果是辅助,它服务的主要高速公路是什么。 这是我的代码,它给了我满分,但我是初学者,必须有更短的方法来编写它。 有人介意清理一下吗?
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.
用于
1) 链式比较
2) f弦
3) 利用 0/1 的布尔值的内联 if 语句
使代码更短
highway_number = int(input())
if 1 <= highway_number <= 99:
direction = 'east/west' if highway_number % 2 else 'north/south'
print(f'The {highway_number} is primary, going {direction}')
elif 100 <= highway_number <= 999:
direction = 'north/south' if highway_number % 2 else 'east/west'
print(f'The {highway_number} is auxiliary, serving the {highway_number%100}, going {direction}')
else:
print(highway_number, 'is not a valid interstate highway number.')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.