如何缩短或清理此 python 代码?
How can I shorten or clean up this python code?
我有一个家庭作业要写一个程序,将高速公路编号作为输入并输出高速公路是主要还是辅助,走east/west,north/south,如果是辅助,它服务于哪条主要公路。这是我的代码,它给了我满分,但我是初学者,必须有更短的编写方法。有人介意清理一下吗?
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.')
我有一个家庭作业要写一个程序,将高速公路编号作为输入并输出高速公路是主要还是辅助,走east/west,north/south,如果是辅助,它服务于哪条主要公路。这是我的代码,它给了我满分,但我是初学者,必须有更短的编写方法。有人介意清理一下吗?
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.')