这是一个我在Delphi、C#和VB.NET教学中经常让学生做的一个例子:输入年份和月份,判断该年是否是闰年;判断该月属于什么季节;该月有多少天。练习对语言的特性的掌握,诸如流程控制、数据类型、输入输出、函数等等。下面是这个问题的Python和Ruby版本。
Python:
Ruby:
Python:
import sys
def IsLeapYear(y):
if ((y % 4==0)and(y % 100!=0))or(y % 400==0):
return True
else:
return False
def Season(m):
if m in [12,1,2]:
return "winter"
elif m in [3,4,5]:
return "spring"
elif m in [6,7,8]:
return "summer"
elif m in [9,10,11]:
return "autumn"
else:
return "error"
def Days(y,m):
if m in [1,3,5,7,8,10,12]:
return 31
if m in [4,6,9,11]:
return 30
if m==2:
if IsLeapYear(y)==True:
return 29
else:
return 28
print "Please input year:"
year=int(sys.stdin.readline(),10)
print "Please input month:"
month=int(sys.stdin.readline(),10)
if IsLeapYear(year)==True:
print "This is Leap year!\n"
else:
print "This is not Leap year!\n"
print "%d is in %s\n" %(month,Season(month))
print "%d has %d days\n" %(month,Days(year,month))
sys.stdin.readline()
def IsLeapYear(y):
if ((y % 4==0)and(y % 100!=0))or(y % 400==0):
return True
else:
return False
def Season(m):
if m in [12,1,2]:
return "winter"
elif m in [3,4,5]:
return "spring"
elif m in [6,7,8]:
return "summer"
elif m in [9,10,11]:
return "autumn"
else:
return "error"
def Days(y,m):
if m in [1,3,5,7,8,10,12]:
return 31
if m in [4,6,9,11]:
return 30
if m==2:
if IsLeapYear(y)==True:
return 29
else:
return 28
print "Please input year:"
year=int(sys.stdin.readline(),10)
print "Please input month:"
month=int(sys.stdin.readline(),10)
if IsLeapYear(year)==True:
print "This is Leap year!\n"
else:
print "This is not Leap year!\n"
print "%d is in %s\n" %(month,Season(month))
print "%d has %d days\n" %(month,Days(year,month))
sys.stdin.readline()
Ruby:
#LeapYear,Season,DaysOfMonth
def IsLeapYear(y)
if ((y % 4==0)and(y % 100!=0))or(y % 400==0)
1
else
0
end
end
def Season(m)
case m
when 12,1,2
"winter"
when 3,4,5
"spring"
when 6,7,8
"summer"
when 9,10,11
"autumn"
else
"error"
end
end
def Days(y,m)
case m
when 1,3,5,7,8,10,12
31
when 4,6,9,11
30
when 2
if IsLeapYear(y)==1
29
else
28
end
end
end
print "Please input year:"
year=readline.to_i
print "Please input month:"
month=readline.to_i
if IsLeapYear(year)==1
print "This is Leap year!\n"
else
print "This is not Leap year!\n"
end
print "#{month} is in #{Season(month)}\n"
print "#{month} has #{Days(year,month)} days\n"
readline()
def IsLeapYear(y)
if ((y % 4==0)and(y % 100!=0))or(y % 400==0)
1
else
0
end
end
def Season(m)
case m
when 12,1,2
"winter"
when 3,4,5
"spring"
when 6,7,8
"summer"
when 9,10,11
"autumn"
else
"error"
end
end
def Days(y,m)
case m
when 1,3,5,7,8,10,12
31
when 4,6,9,11
30
when 2
if IsLeapYear(y)==1
29
else
28
end
end
end
print "Please input year:"
year=readline.to_i
print "Please input month:"
month=readline.to_i
if IsLeapYear(year)==1
print "This is Leap year!\n"
else
print "This is not Leap year!\n"
end
print "#{month} is in #{Season(month)}\n"
print "#{month} has #{Days(year,month)} days\n"
readline()