如果路過的朋友們發現錯誤或有意見,歡迎指正和提出。當然,對一些題目沒頭緒時,會參考一下前輩們的代碼,在此表示感謝。
第5章 5-4
#!/usr/bin/env python#coding:utf-8year = int(raw_input('請輸入年份:'))if (year % 4==0 and year % 100!=0) or (year % 400==0) : print '%d是閏年' % yearelse : print '%d不是閏年' % year
5-5
#!/usr/bin/env python#coding:utf-8dollar = float(raw_input('請輸入美元數目:'))cent = int(dollar * 100)a = cent/25cent = cent%25if cent>0: b = cent/10cent = cent%10if cent>0: c = cent/5cent = cent%5if cent >0: d = cent#先判斷變數是否存在,再進行相應輸出,避免出現NameErrorif locals().has_key('a'): print '\n%d枚25美分' % aif locals().has_key('b'): print '\n%d枚10美分' % bif locals().has_key('c'): print '\n%d枚5美分' % cif locals().has_key('d'): print '\n%d枚1美分' % d
5-6
#!/usr/bin/env python#coding:utf-8string = raw_input('請輸入運算式:')if len(string.split('+'))==2 : temp = string.split('+') print float(temp[0]) + float(temp[1])if len(string.split('-'))==2 : temp = string.split('-') print float(temp[0]) - float(temp[1])if len(string.split('*'))==2 : temp = string.split('*') print float(temp[0]) * float(temp[1])if len(string.split('/'))==2 : temp = string.split('/') print float(temp[0]) / float(temp[1])if len(string.split('%'))==2 : temp = string.split('%') print float(temp[0]) % float(temp[1])if len(string.split('**'))==2 : temp = string.split('**') print float(temp[0]) ** float(temp[1])
5-15
#!/usr/bin/env python#coding:utf-8num1 = int(raw_input('請輸入第一個數:'))num2 = int(raw_input('請輸入第二個數:'))if num1 > num2 : temp = num2else : temp = num1while temp > 0: if num1 % temp==0 and num2 % temp == 0 : yue = temp break temp -= 1bei = num1*num2/yueprint yue,' ',bei