首页 > 解决方案 > 从硬编码打印是可行的,但是如何从 Python 中定义的方法打印这些变量输入的值?

问题描述

我正在使用 Sublime Text 3 并在带有 Python 解释器 3.6.3 的 Ubuntu 16.04 终端中运行代码。这是我试图解决的部分代码:

    import sys
    print(sys.version_info)
    import math
    import cmath
    import datetime
    import random as RAN
    from tabulate import tabulate

    class Person:

        def __init__(self, firstName, lastName, birthdate, email, idx):
            self.firstName = firstName
            self.lastName = lastName
            self.birthdate = birthdate
            self.email = email
            self.idx = idx
            self._age = None
            self._age_last_recalc = None
            self._recalc_age()
        def _recalc_age(self):
            today = datetime.date.today()
            age = today.year - self.birthdate.year
            if today < datetime.date(today.year, self.birthdate.month, self.birthdate.day):
                age -= 1
            self._age = age
            self._age_last_recalc = today
        def age(self):
            if (datetime.date.today() > self._age_last_recalc):
                self._recalc_age()
            return self._age

    def KeyInPosNumber(n, lower, upper):
        while True:
            try:
                n = int(input('Enter> '))
            except ValueError:
                print("Invalid input. Please try again.\n")
                continue
            if not n in range (lower, upper):
                print("Value cannot be under {0} or exceed {1}. Please try again.\n".format(lower, upper))
                continue
            else:
                break

    def KeyInString(n):
        while True:
            try:
                n = str(input('Enter> '))
            except StandardError:
                print("Error encountered! Please try again.\n")
                continue
            else:
                break

    def main():         
        girl = Person("Jane", "Doe", datetime.date(1992, 9, 15), "jane.doe@em.com", "53A")
        print("")
        print("Example student:") #Here's the hard-coded version
        print(girl.firstName)
        print(girl.lastName)
        print(girl.age())
        print(girl.email)
        print(girl.idx)
        print("")
        print("")

        print("Key in the student's birth year in the format YYYY.")
        BYear = 0; 
        BYear = KeyInPosNumber(BYear, 1900, 2015)
        print("\nKey in the student's birth month in the format MM.")
        BMonth = 0; 
        BMonth = KeyInPosNumber(BMonth, 1, 13)
        print("\nKey in the student's birth day number in the format DD.")
        BDay = 0; 
        BDay = KeyInPosNumber(BDay, 1, 32)
        print("\nKey in the student's first name.")
        FName = ""; 
        FName = KeyInString(FName)
        print("\nKey in the student's last name.")
        LName = ""; 
        LName = KeyInString(LName)
        print("\nKey in the student's email address (without '@' and domain.)")
        EMail = ""; 
        EMail = KeyInString(EMail)
        print("\nKey in the student's registration index.")
        RIndex = ""; 
        Rindex = KeyInString(RIndex)

        kid = Person(FName, LName, datetime.date(BYear, BMonth, BDay), EMail, RIndex) #Here's the input version
        print("")
        print(kid.firstName)
        print(kid.lastName)
        print(kid.age())
        print(kid.email)
        print(kid.idx)      

    if __name__ == '__main__':
        main()

我可以打印出硬编码的女孩,但不能打印出输入的孩子。花了很多时间试图通过我的教练和互联网解决这个问题。

终端错误指向该行:

    kid = Person(FName, LName, datetime.date(BYear, BMonth, BDay), EMail, RIndex)

错误说:TypeError:需要一个整数(得到类型 NoneType)

谢谢您的帮助。

标签: pythonfunctionterminalubuntu-16.04

解决方案


KeyInString(n) 函数和其他函数没有返回值,因此变量中没有存储任何内容。

尝试这个:

def KeyInString(n):
    while True:
        try:
            n = str(input('Enter> '))
        except StandardError:
            print("Error encountered! Please try again.\n")
            continue
    return n

而且您不一定需要向函数传递我推荐的参数:

def KeyInString():
    while True:
        try:
            n = str(input('Enter> '))
        except StandardError:
            print("Error encountered! Please try again.\n")
            continue
    return n

调用它使用:

EMail = KeyInString()

但一如既往,你是老板,随你喜欢:)


推荐阅读