You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python预订系统如何将校验函数与收据关联,获取校验后的正确信息

问题核心原因

你定义的date()、checkemail()、phone()三个输入校验函数仅做了合法性判断和提示,没有返回校验通过的输入内容,因此在booking_form中赋值给Email、ContactNumber、Date变量的都是默认返回值None,最终写入CSV和打印收据时都会出现数据异常。同时收据打印部分存在两处逻辑错误:重复调用date()会触发二次日期输入、调用不存在的局部变量email会直接报错。


修改方案

1. 调整校验函数,校验通过后返回对应内容

  • 校验通过时主动return符合要求的输入值
  • 递归调用校验函数时也要加return,保证最内层的正确结果能逐层返回

2. 修正收据打印的错误逻辑

  • 打印日期直接使用已经赋值的Date变量,不要重复调用date()
  • 打印邮箱直接使用已经赋值的Email变量,不需要再次调用校验函数

修改后完整可运行代码

import datetime
import re
import csv
from rich.console import Console # 代码中用到了console.input,需引入对应依赖

console = Console()

def date():
    inputDate = input("Enter the booking date in format 'dd/mm/yy' : ")
    day, month, year = inputDate.split('/')
    isValidDate = True
    try:
        datetime.datetime(int(year), int(month), int(day))
    except ValueError:
        isValidDate = False
    if(isValidDate):
        print("Input date is valid ..")
        return inputDate # 新增:返回校验通过的日期
    else:
        print("Input date is not valid..")
        return date() # 新增:返回递归调用的结果


def validateEmail(email):
    return re.match(r'[\w-]{1,20}@\w{2,20}\.\w{2,3}$', email)


def checkemail():
    email = console.input('[bright_white]Please enter your email address: [/]')
    valid = validateEmail(email)
    if valid:
        print(email, 'is valid')
        return email # 新增:返回校验通过的邮箱
    else:
        print("invalid email format", email)
        return checkemail() # 新增:返回递归调用的结果

def phone():
    phoneno = console.input('[bright_white]Please enter your phone number :[/] ')
    patter = r"^(1|8|9)[0-9]{7}"
    if re.match(patter, phoneno) and len(phoneno) == 8:
        print("Valid")
        return phoneno # 新增:返回校验通过的手机号
    else:
        print("Invalid")
        return phone() # 新增:返回递归调用的结果


def booking_form():
    bookings = []
    FirstName = input('Please enter your first name: ')
    LastName = input('Please enter your last name: ')
    Email = checkemail()
    ContactNumber = phone()
    Date = date()
    Time = input('Enter time in 00:00 AM/PM format:')
    Gym = input("Please Enter the Name of the Gym Again to Ensure that to be the Correct one:  ")
    Commentsrequest = input('Comments/Additional Request: ')

    bookings.append(FirstName)
    bookings.append(LastName)
    bookings.append(Email)
    bookings.append(ContactNumber)
    bookings.append(Date)
    bookings.append(Time)
    bookings.append(Gym)
    bookings.append(Commentsrequest)

    with open("booking.csv", 'a', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(bookings)

    # 修正打印逻辑
    print(" Date:", Date)
    print(" Time:", Time)
    print(" First Name:", FirstName)
    print(" Last Name:", LastName)
    print(" Email:", Email)
    print(" Phone Number:", ContactNumber)
    print(" Chosen Location [Area/Gym]:", Gym)
    print(" Additional Notes/Requests:", Commentsrequest)
    print("**********************************************************************", )
    print("|         Thank You for Using the Volleyball Booking System          |", )
    print("|            You have Successfully Booked a Court/Gym                |", )
    print("|             Please Screenshot this Receipt to Keep                 |", )
    print("|                      as Proof of Booking                           |", )
    print("|          Have a Good Day, We will see you on the Court!!           |", )
    print(
        "                          ★★★★★★★★★★★★                              ")
    print("**********************************************************************", )
    exit()

# 启动预订流程
if __name__ == "__main__":
    booking_form()

内容的提问来源于stack exchange,提问作者vedha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:45:05