如何获得可变输入以进行打印?

时间:2018-08-22 00:36:58

标签: python-3.x input printing

我正在尝试输入要打印的课堂作业。

# Program Name: BadDate.py 
# Function:     This program determines if a date entered by the user is valid.  
# Input:        Interactive
# Output:       Valid date is printed or user is alerted that an invalid date was entered.

validDate = True
MIN_YEAR = 0
MIN_MONTH = 1
MAX_MONTH = 12
MIN_DAY = 1
MAX_DAY = 31

month = float (input("Enter Month "))
day = float (input("Enter Day "))
year = float (input("Enter Year "))


# Get the month, then the day, then the year
# housekeeping()

# Check to be sure date is valid

if int(year) <= MIN_YEAR: # invalid year
    validDate = False
elif int(month) < MIN_MONTH or int(month) > MAX_MONTH: # invalid month
    validDate = False
elif int(day) < MIN_DAY or int(day) > MAX_DAY: # invalid day
    validDate = False

# Test to see if date is valid and output date and whether it is valid or not
if validDate == True:
    print(str(month)+'/'+str(day)+'/'+str(year) " is a valid date") 
else:
    print(str(month)+'/'+str(day)+'/'+str(year) " is an invalid date")

# endOfJob()

获取日期时出现语法错误。我需要这些语句来打印用户输入的日期。谢谢。

2 个答案:

答案 0 :(得分:0)

如果您仔细查看给出的错误,可能会发现它。 现在,作为新用户,解码这些错误及其来源可能似乎具有挑战性。包括SyntaxError堆栈跟踪对您会有所帮助,因此我们可以帮助您向您说明问题的发生速度。

无论如何,您在调用print函数时仅缺少2个简单的串联/加运算符(+),因此,这是固定代码:

# Program Name: BadDate.py 
# Function:     This program determines if a date entered by the user is valid.  
# Input:        Interactive
# Output:       Valid date is printed or user is alerted that an invalid date was entered.

validDate = True
MIN_YEAR = 0
MIN_MONTH = 1
MAX_MONTH = 12
MIN_DAY = 1
MAX_DAY = 31

month = float (input("Enter Month "))
day = float (input("Enter Day "))
year = float (input("Enter Year "))


# Get the month, then the day, then the year
# housekeeping()

# Check to be sure date is valid

if int(year) <= MIN_YEAR: # invalid year
    validDate = False
elif int(month) < MIN_MONTH or int(month) > MAX_MONTH: # invalid month
    validDate = False
elif int(day) < MIN_DAY or int(day) > MAX_DAY: # invalid day
    validDate = False

# Test to see if date is valid and output date and whether it is valid or not
if validDate == True:
    print(str(month)+'/'+str(day)+'/'+str(year) + " is a valid date") 
else:
    print(str(month)+'/'+str(day)+'/'+str(year) + " is an invalid date")

# endOfJob()

答案 1 :(得分:0)

您可以将所有这些组合成一个条件:

month = int(input("Enter Month "))
day = int (input("Enter Day "))
year = int (input("Enter Year "))
if 1<=day<=31 and year>0 and 1<=month<=12:
    print(str(month)+'/'+str(day)+'/'+str(year)+ " is a valid date") 
else:
    print(str(month)+'/'+str(day)+'/'+str(year) +" is an invalid date")

尽管已给出,但这意味着放置Feb 30 02之类的东西会被认为是有效的,等等