簡體   English   中英

Python 代碼沒有實現正確的輸出?

[英]Python code not achieving correct output?

我有一個學校到期的項目,除了一部分之外正在工作。 我有一個包含生日的清單,我通過每個人的生日得到年齡,然后將它們歸類為成人、兒童、老年人或嬰兒/幼兒。 幼兒/嬰兒必須至少有一名成人/老年人陪伴,我在代碼末尾考慮到了這一點。 我有每個年齡組的運行總數和一般計數。 但是,當嬰兒/幼兒在沒有父母的情況下提交時,我嘗試減少計數以消除條目,因為它無效但最后打印出來?

import datetime
# import datetime fucntion for use in determining ages
today = datetime.datetime.now()
# set variable for today's current date
thirtyone = ['01', '03', '05', '07', '08', '10', '12']
# distinguish which months have 31 days to validate date
thirty = ['04', '06', '09', '11']
# distinguish which months have 30 days to validate date
adults = 0
# total number of adults for one booking
children = 0
# total number of children for one booking
baby_todds = 0
# total number of babies for one booking
seniors = 0
# total number of seniors for one booking
a_cost = 0
# total cost of adults for one booking
c_cost = 0
# total cost of children for one booking
s_cost = 0
# total cost of seniors for one booking
tot_adult = 0
# running total for adults over day
tot_child = 0
# running total for children over day
tot_bab = 0
# running total for babies over day
tot_sen = 0
# running total for seniors over day
total_birthdays = []
while True:
    # run validation for total number of people
        total_people = input('How many people are going?: ').strip()
        # get total number of people and strip to remove unnecessary spacing
        if total_people == '':
        # if total people entered as blank
            print("* you haven't entered anything.")
            # let user know error
            continue
            # go back to top of loop to re-enter total number of people
        elif re.search('[a-z]', total_people):
        # if there are lowercase letters in total people
            print("* entry can't contain letters. please try again with only numbers.")
            # let user know error
            continue
            # go back to top of loop to re-enter total number of people
        elif re.search('[A-Z]', total_people):
        # if there are uppercase letters in total people
            print("* entry can't contain letters. please try again with only numbers.")
            # let user know error
            continue
            # go back to top of loop to re-enter total number of people
        elif re.search('[~!@#£€$¢¥§%^&*()\\-_+={}[]|/:;"\'<>,.?]', total_people):
        # if there are symbols in total people
            print("* entry can't contain letters. please try again with only numbers.")
            # let user know error
            continue
            # go back to top of loop to re-enter total number of people
        elif int(total_people) < 1:
        # if total people as an integer is less than 1
            print('* must have at least one guest.')
            # let user know error
            continue
            # go back to top of loop to re-enter total number of people
        else:
        # if none of these conditions apply, entry is valid
            break
            # exit out of while loop
total_people = int(total_people)
# convert total people to integer for furture use
x = True
# set x variable to true
while x == True:
# while x is true, loop can run
    for person in range(total_people):
    # for each person as one of total people
        while True:
        # run validation for birthday
            birthday = input('Birthday (MM/DD/YYYY): ').strip()
            # get total number of people and strip to remove unnecessary spacing
            if birthday == '':
            # if birthday entered as blank
                print("* you haven't entered anything.")
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif re.search('[a-z]', birthday):
            # if there are lowercase letters in birthday
                print("* birthday can't contain letters. please try again in (MM/DD/YYYY) format.")
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif re.search('[A-Z]', birthday):
            # if there are uppercase letters in birthday
                print("* birthday can't contain letters. please try again in (MM/DD/YYYY) format.")
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif re.search('[~!@#£€$¢¥§%^&*()\\-_+={}[]|/:;"\'<>,.?]', birthday):
            # if there are symbols in birthday
                print("* birthday can't contain an invalid symbol. please try again in (MM/DD/YYYY) format.")
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            try:
            # if content is correct, check format
                datetime.datetime.strptime(birthday, '%m/%d/%Y')
                # if birthday can be made into a date format, is valid
            except ValueError:
            # if birthday can't be made into a date format
                print('* incorrect date format, should be (MM/DD/YYYY)')
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            birthdays = birthday.split('/')
            # format now correct, split to run validation for dates
            if len(birthdays[2]) != 4:
            # if the year does not have 4 numbers
                print('* invalid year. please try again.')
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif int(birthdays[2]) < 1900:
            # if the year is less thyan 1900
                print('* invalid year. please try again.')
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif datetime.datetime.strptime(birthday,'%m/%d/%Y') > today:
            # if the date entered is in the future
                print('* invalid date. please try again.')
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
            elif birthdays[0] in thirtyone:
            # if the month is in the list of months with thirty one days
                if int(birthdays[1]) <= 31:
                # if the day is less than or equal to 31
                    break
                    # birthday is valid, exit out of loop
                else:
                # if the day is more than 31
                    print('* invalid day. please try again.')
                    # let user know error
                    continue
                    # go back to top of loop to re-enter birthday
            elif birthdays[0] in thirty:
            # if the month is in the list of months with thirty days
                if int(birthdays[1]) <= 30 :
                # if the day is less than or equal to 30
                    break
                    # birthday is valid, exit out of loop
                else:
                # if the day is more than 30
                    print('* invalid day. please try again.')
                    # let user know error
                    continue
                    # go back to top of loop to re-enter birthday
            elif birthdays[0] == '02':
            # if the month is february
                if int(birthdays[1]) > 29:
                # if the day is more than 29
                    print('* invalid date. please try again.')
                    # let user know error
                    continue
                    # go back to top of loop to re-enter birthday
                elif int(birthdays[1]) == 29:
                # if the day is exactly equal to 29
                    if int(birthdays[2]) % 4 == 0 and int(birthdays[2]) % 10 != 0:
                    # if the year is exactly divisible by 4 but not by 10
                        break
                        # birthday is valid (valid leap year), exit out of loop
                    else:
                    # if the year is not a valid leap year
                        print('* invalid date. please try again.')
                        # let user know error
                        continue
                        # go back to top of loop to re-enter birthday
                else:
                # if the day is less than or equal to 28
                    break
                    # birthday is valid, exit out of loop
            else:
            # if the month is more than 12
                print('* invalid month. please try again.')
                # let user know error
                continue
                # go back to top of loop to re-enter birthday
        total_birthdays.append(birthday)
        # append validated birthday to total birthdays list
    for birthday in total_birthdays:
    # for each valid birthday in total birthdays loop
        birth_date = datetime.datetime.strptime(birthday,'%m/%d/%Y')
        # convert birthday to workable date format
        age = today - birth_date
        # take birthday away from today's date
        age = age.total_seconds()/(365*24*3600)
        # find numerical value for age by dividing total seconds of answer by seconds in one year
        if age < 3:
        # if age is less than 3
            baby_todds += 1
            # add 1 to babies total
            tot_bab += 1
            # add 1 to babies running total
        elif age < 12:
        # if age is less than 12
            children += 1
            # add 1 to children total
            tot_child += 1
            # add 1 to children running total
        elif age >= 65:
        # if age is greater than or equal to 65
            seniors += 1
            # add 1 to seniors total
            tot_sen += 1
            # add 1 to seniors running total
        else:
        # if none of above, is adult by default
            adults += 1
            # add 1 to adults total
            tot_adult += 1
            # add 1 to adults running total
    if baby_todds == 0:
        x = False
    elif baby_todds > 0 and (adults > 0 or seniors > 0):
    # if there are babies/toddlers but at least one adult/senior
        x = False
        # suitable parental advisory, break out of loop
    else:
    # if there are babies/toddlers but no adults or seniors
        print()
        # add break
        print('Babies and toddlers can not go unsupervised.')
        # let user know error
        print('Please re-enter appropriate birth dates.')
        # request to re-enter birthdays
        tot_bab -= baby_todds
        # removes last entry from running total for babies/toddlers
        baby_todds = 0
        # resets baby/toddlers to 0
        tot_child -= children
        # removes last entry from running total for children
        children = 0
        # resets children to 0
        x = True
        # go right back to start of loop
print(baby_todds)
print(tot_bab)
print(children)
print(tot_child)

例如,我輸入生日 02/19/2020 和 03/20/2019 時出現錯誤(沒有成人/老年人)並要求我再次輸入。 所以我輸入 02/19/1990 和 02/29/20000 這是有效的。 但是 baby_todds 和 tot_bab 仍然打印為 2 嗎? 我發誓我已經嘗試了一切,但沒有任何效果。 就好像它完全跳過了那個代碼。

您的問題是,當您返回循環的開頭並從用戶那里接收新日期時,您不會創建新的total_birthdays列表,而是附加您在循環之前創建的列表,該列表還包含上一次迭代的日期的循環。 如果您將total_birthdays = []行移動到從用戶讀取日期的循環內,它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM