python中的字符串

想要编写一个使用字符串显示出生日期的程序。请检查代码:

dob = int(input("enter your birth day"))
if dob > 31 or dob < 1:
   print("invalid")
mob = int(input("enter your birth month"))
if mob > 12 or mob < 1:
   print("invalid")
yob = int(input("enter your birth year"))
date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(date[0], date[1], date[2])
print(bday)

输出:

我想以可以打印有效日期的方式制作此程序,例如: 32/23/2020无效,因此不能打印。 请帮帮我:)

评论
luyao
luyao

You have to use or operator, your value will never be greater than 31 and lower than 1 at the same time

if dob > 31 or dob < 1

另外,您可能想再询问一次,直到该值有效为止,而不仅仅是告诉用法,为此使用while循环

dob = 0
while dob > 31 or dob < 1:
    dob = int(input("enter your birth day: "))

mob = 0
while mob > 12 or mob < 1:
    mob = int(input("enter your birth month: "))

yob = int(input("enter your birth year: "))

date = [dob, mob, yob]
bday = "Your birthday is on: {0}/{1}/{2}".format(*date) # * operator is for unpacking the list
print(bday)

演示版

enter your birth day: 32
enter your birth day: 35
enter your birth day: 15
enter your birth month: 55
enter your birth month: 20
enter your birth month: 10
enter your birth year: 1950
Your birthday is on: 15/10/1950
点赞
评论