date = raw_input()
while date!="END" or date!="end":
day = date[0:2]
month = date[3:5]
monthsingle = date[3:5]
monthsingle =str(int(monthsingle))
monthsingle = int(monthsingle)
我在这里要完成的是将月份编号分配给monthsingle
,以便稍后在我的代码中使用它。问题是用户可以输入" 02"二月。如果没有此错误,我该怎么做:
monthsingle =str(int(monthsingle))
ValueError: invalid literal for int() with base 10: ''
答案 0 :(得分:1)
如果用户输入的长度少于四个字符,则date[3:5]
将为空字符串。
在尝试将输入字符串转换为整数之前,您可以检查输入字符串是否有效,或者捕获异常并为用户提供有用的错误消息。意外的用户输入不应导致程序崩溃。
while True:
print('Please enter a date in format "dd/mm" or "end".')
date = raw_input() # use input() if you use python 3
if date.lower() == 'end':
print('good bye')
break
try:
day = int(date[0:2])
month = int(date[3:5])
print('Day is %d and month is %d' % (day, month))
# Day and month are integers.
# You should check that it's a real date as well.
except ValueError:
# could not convert to integer
print('invalid input!')
答案 1 :(得分:0)
在此实施中,您可以修剪' 0' 0在开始时:
monthsingle = date[3:5].lstrip('0')
或查看日期[3:5]:好像有一个点。
答案 2 :(得分:0)
It is not a problem that the user is allowed to type 02 for February.错误消息表明问题是monthsingle
为空(''
)。如果你将一个字符串切成了它的末尾;你得到一个空字符串。
这意味着输入不是dd/mm
格式。
要在不使用datetime.strptime()
功能的情况下解析日期:
while True:
try:
day, month = map(int, raw_input("Enter date dd/mm: ").split('/'))
# validate day, month here...
except ValueError:
print 'invalid input, try again'
else:
break
# use day, month to get the next date...
# you could use datetime module to check your answer:
from datetime import date, timedelta
print(date(date.today().year, month, day) + timedelta(1))
答案 3 :(得分:0)
def generate_next_date(day,month,year):
#Start writing your code here
if((year%400==0 or year%4==0) and month==2):
next_day=day+1
next_month=month
next_year=year
elif(month==2 and day==28):
next_day=1
next_month=month+1
next_year=year
elif(month==12 and day==31):
next_day=1
next_month=1
next_year=year+1
elif(day==31 ):
next_day=1
next_month=month+1
next_year=year
elif((day==30) and (month==4 or month==6 or month==9 or month==11)):
next_day=1
next_month=month+1
next_year=year
else:
next_day=day+1
next_month=month
next_year=year
print(next_day,"-",next_month,"-",next_year)
generate_next_date(28,2,2015)
答案 4 :(得分:0)
Java 中的解决方案
<块引用>实现一个程序来生成和显示给定日期的下一个日期。日期将以日、月和年的形式提供,如下表所示。输出应以以下格式显示:日-月-年。假设:输入将始终是一个有效的日期。
class NextDate
{
public static void main(String[] args)
{
// Implement your code here
int day = 31,month = 12, year=15,monthLength;
year = 2000+year;
char leap;
if((year % 4==0) & (year % 100 == 0) || (year % 400 == 0))
{
leap = 'y';
}
else
{
leap = 'n';
}
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
monthLength = 31;
}
else if(month == 2)
{
if(leap == 'y')
{
monthLength = 28;
}
else
{
monthLength = 29;
}
}
else
{
monthLength = 30;
}
if(day < monthLength)
{
day++;
}
else if(month == 12 & day == monthLength)
{
day = 1;
month=1;
year++;
}
System.out.println(day+"-"+month+"-"+year);
}
}