我目前正在制作一个程序,该程序获取飞行规范数据并将飞行细节输出给用户(这是一个小程序,只是为了好玩(。规范必须遵循某种格式。示例:GLA 2 25 S F(机场名称、行李数量、年龄、用餐类型和座位等级(,我想知道是否有办法验证这一点,并确保用户输入此格式而不会导致程序崩溃。
当前代码:
import time
def main():
AMS_DESTINATION = "Schiphol, Amsterdam"
GLA_DESTINATION = "Glasgow, Scotland"
AMS_PRICE = 150.00
GLA_PRICE = 80.00
flightSpecification = str(input("Enter Flight Specification: "))
flightDestination = flightSpecification[0:3]
bagCount = int(flightSpecification[4])
baggageCost = float((bagCount - 1) * 20)
if flightDestination.lower() != 'ams' and flightDestination.lower() != 'gla':
print("Please enter a valid flight specification! [LLL 0 00 L L]")
time.sleep(2)
main()
if flightDestination.lower() == 'ams':
print(f"Destination: {AMS_DESTINATION}")
print(f"Flight cost: £{AMS_PRICE}")
elif flightDestination.lower() == 'gla':
print(f"Destination: {GLA_DESTINATION}")
print(f"Flight cost: £{GLA_PRICE}")
print(f"Number of bags: {bagCount}")
print(f"Baggage Cost: £{baggageCost}")
main()
谢谢!
您可以使用以下模式:
while True:
flightSpecification = input("Enter Flight Specification: ") # input() already returns a string
flightDestination = flightSpecification[0:3]
if flightDestination.lower() != 'ams' and flightDestination.lower() != 'gla':
print("Please enter a valid flight specification! [LLL 0 00 L L]")
continue # goes back to the beginning of the while loop - skips the break instruction
# add other input validations as needed
break # exits from the while loop
还可以考虑将异常与try/except一起使用,使其更具Python风格,并提供更好的开发人员体验
您可以使用正则表达式进行验证。
[A-Z]{3} d d{2} [A-Z] [A-Z]
试用
说明:
[A-Z]{3}
:匹配三个连续字母,后跟一个空格d
:匹配一个数字,后跟一个空格d{2}
:匹配两个连续数字[A-Z]
:匹配单个字母
在python中,您可以使用re
模块来实现这一点
import re
flightSpecification = input("Enter Flight Specification: ") # input already returns a string
if re.match(r"[A-Z]{3} d d{2} [A-Z] [A-Z]", flightSpecification, flags=re.IGNORECASE):
# this is a valid flightspec. Do whatever
else:
# Not valid. Do whatever
您还可以使用捕获组来提取字符串的相关部分,如下所示:([A-Z]{3}) (d) (d{2}) ([A-Z]) ([A-Z])
m = re.match(r"([A-Z]{3}) (d) (d{2}) ([A-Z]) ([A-Z])", flightSpecification, flags=re.IGNORECASE)
if m:
# valid.
print("airport = ", m.group(1))
print("bags = ", m.group(2))
print("age = ", m.group(3))
print("meal type = ", m.group(4))
print("seat = ", m.group(5))
要强制AMS
和GLA
中的任何一个作为机场,请将[A-Z]{3}
替换为(AMS|GLA)
尝试
如果您想纠缠用户直到他们输入有效的输入,请参阅询问用户输入直到他们给出有效的响应