繁体   English   中英

Python 初学者编码器问题

[英]Python Beginner Coder Problems

我正在处理 UI 并且无法通过第二个 function 运行我的代码。 UI的初始function应该取客户的全名并说(“Hello + full_name),然后取客户的出生日期并从当前日期中减去它来计算客户的年龄。这段代码的第一部分是很明显,我只是不知道如何将代码传递到代码的第二部分,代码打印出“对不起,我们目前无法创建您的帐户”或“让我们继续下一步”。任何帮助或建议会有所帮助。

from datetime import datetime

full_name = input("Hi my name is Jacko. What is your full name?")
print ("Hello" + full_name)

class Jacko:
    dob = input("Input your birthday, please: ")
    date_of_birth = datetime.strptime(dob, "%Y %m %d")
    current_date = datetime.today()
    current_age = (current_date - date_of_birth) /365
    
    def __init__(self, name):
        self.name = name
            
    def age (self):
        self.current_age = current_age
        if self.current_age < 21:
            print ("Sorry we can not create your account at this time")
        else:
            print ("Let's move forward with the next steps")

这个例子中有很多事情没有正确实现。 例如,我看不出您打算如何使用Jacko class。

其次,年龄应该是由用户提供的,所以它应该在__init__中,而不是 class 属性。 Class 属性对于 class 的所有实例完全相同,因此除非您希望所有用户具有相同的年龄,否则年龄将进入__init__

在计算current_age时,我假设我们会对整年感兴趣,因此使用 integer 除法而不是常规除法。 所以我会像这样重写代码:

from datetime import datetime

class Jacko:    
    def __init__(self, name, dob):
        print(f'Hello {name}')
        self.name = name
        self.dob = datetime.strptime(dob, "%Y %m %d")
        self.current_age_years = datetime.today().year - self.dob.year
            
    def age (self):
        if self.current_age_years < 21:
            print ("Sorry we can not create your account at this time")
        else:
            print ("Let's move forward with the next steps")


if __name__ == '__main__':
    full_name = input("Hi my name is Jacko. What is your full name? ")
    dob = input('What is your date of birth?' )
    
    jc = Jacko(full_name, dob)
    jc.age()    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM