这是我的代码,用于尝试找出访问 18+ 网站的人的年龄 ( https://www.reddit.com/r/beginnerprojects/comments/3hrbpo/project_verifying_a_users_age/ ) 我有两个问题。 1)我不知道如何将列表网站添加到我的 else 字符串中。 2)我想知道是否有办法为 currentDate 导入当前年份,这样就不必手动输入。再次感谢,并对草率的代码表示歉意,我对 Python 还是新手!
import datetime
websites = ["www.youtube.com", "www.quora.com", "www.twitter.com"]
while True:
currentDate = 2015
print("WARNING: THIS WEBSITE IS FOR 18 YEARS OR UP")
userAge = int(raw_input("What is the year of your birth? "))
if userAge + 18 <= currentDate:
print "Welcome!"
break
elif userAge + 18 > currentDate:
print ("We're sorry, but this website isn't for you, try some of these websites: ")
continue
最佳答案
给你:
- 您希望 date.today() 获取当前日期
- 您想要使用 string.format() 和 string.join() 将列表连接在一起并将其内容插入到输出中
- 不需要
elif
子句 -else
处理“otherwise”条件(因为您的elif
与您的if 相反
)
代码:
from datetime import date
websites = ["www.youtube.com", "www.quora.com", "www.twitter.com"]
while True:
print("WARNING: THIS WEBSITE IS FOR 18 YEARS OR UP")
userAge = int(raw_input("What is the year of your birth? "))
if userAge + 18 <= date.today().year:
print "Welcome!"
break
else:
print ("We're sorry, but this website isn't for you, try some of these websites: {}".format(",".join(websites))
continue
关于python - 添加列表和字符串并导入当前年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33272851/