日 - 循环

Susan Sarandon
Susan Sarandon原创
2024-11-26 01:25:121046浏览

Day - Looping

编写一个计算年龄的程序:

from datetime import datetime

dob = input("Enter your Date of Birth (yyyy-mm-dd): ")
dob_date = datetime.strptime(dob, "%Y-%m-%d")
print(dob_date)

current_date = datetime.now()

age = current_date.year - dob_date.year
print(f"Your age is {age}")

datetime.now() -datetime.now() 是 Python 的 datetime 模块中的一个函数,它以 datetime 对象的形式返回当前本地日期和时间,包括微秒。

strptime() - Python 中的 strptime() 方法用于将表示日期和/或时间的字符串解析(转换)为日期时间对象。它是日期时间模块的一部分。

Enter your Date of Birth (yyyy-mm-dd): 1993-03-26
1993-03-26 00:00:00
Your age is 31

另一种方法:

如果结果为负数,请使用此方法

from datetime import date
birth_year = 1993
birth_month = 3
birth_day = 26
today = date.today()
year = today.year - birth_year
month = today.month - birth_month
days = today.day - birth_day

if month<0:
    year = year - 1
    month = 12+month

if days<0:
    month=month-1
    days = 30 + days

print (f"You are {year} Years {month} Months {days} Days Old")

You are 31 Years 7 Months 29 Days Old

使用relativedelta的替代方法:

from datetime import datetime
from dateutil.relativedelta import relativedelta

dob = input("Enter date of birth in yyyy-mm-dd format: ")

dob_date = datetime.strptime(dob, "%Y-%m-%d")

today = datetime.now()

difference = relativedelta(today, dob_date)

print(difference.years, " Years ", difference.months, " Months ", difference.days, " days")

relativedelta 是 Python 中 dateutil 模块的一部分,它提供了比标准库的 timedelta 更强大的日期和时间操作操作。它允许您执行诸如添加或减去月份和年份之类的操作,而 timedelta 无法直接处理这些操作。

Enter date of birth in yyyy-mm-dd format: 1993-03-26
31  Years  7  Months  30  days

while 循环的一些示例:

no = 1
while no<=5:
    print(no, end=' ')
    no+=1
1 1 1 1 1
no = 1
while no<=10:
    print(no, end=' ')
    no+=1
1 2 3 4 5 6 7 8 9 10
no = 10
while no>=1:
    print(no, end=' ')
    no-=1
10 9 8 7 6 5 4 3 2 1
no = 1
while no<=10:
    print(no, end=' ')
    no+=2
1 3 5 7 9
no=2
while no<=10:
    print(no, end=' ')
    no+=2
2 4 6 8 10
no = 3
while no<=10:
    print(no, end=' ')
    no+=3
3 6 9
no = 1
total = 0
while no<=5:
    total = total + no
    no+=1

print(total)
15
no = 1
while no<=5:

    print(no*3, end=' ')


    no+=1
3 6 9 12 15
no = 1
while no<=10:
    print(no,"*5=",no*5, end='\n')
    no+=1
1 *5= 5
2 *5= 10
3 *5= 15
4 *5= 20
5 *5= 25
6 *5= 30
7 *5= 35
8 *5= 40
9 *5= 45
10 *5= 50
no = 1
while no<=10:
    print(no, end = ' ')
    if no==9:
        no = 0
    no+=2
1 3 5 7 9 2 4 6 8 10

以上是日 - 循环的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn