下面的代码是这两天看 Python 核心编程的时候做的部分课后练习
1 2 3 4 5 6 7 8 9 10 11 def mult (x,y ) : '返回两个数x和y的乘积' return int (x) * int (y) a = raw_input('输入数a:' ) b = raw_input('输入数b:' ) print 'a * b = ' , mult(a,b)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 while True : score = raw_input('输入分数:' ) score = int (score) if score > 100 or score < 0 : print '输入分数无效,程序退出' break elif score >= 90 : print '%d is rank A' % score elif score >= 80 : print '%d is rank B' % score elif score >= 70 : print '%d is rank C' % score elif score >= 60 : print '%d is rank D' % score else : print '%d is rank F' % score
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 def isLeap (year ) : year = int (year) if (year % 4 == 0 and year % 100 != 0 ) or year % 400 == 0 : return True else : return False year = raw_input('输入一个年份:' ) if (isLeap(year)) :print year, '是闰年' else :print year, '不是闰年'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 money = raw_input('输入任意小于1 美元的金额:' ) print money,'美元换算结果' money = float (money) money *= 100 money = int (money) cent25 = money / 25 money %= 25 cent10 = money / 10 money %= 10 cent5 = money / 5 money %= 5 cent1 = money if cent25 : print '25美分*' ,cent25 if cent10 : print '10美分*' ,cent10 if cent5 : print '5美分*' ,cent5 if cent1 : print '1美分*' ,cent1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 def operator (str ) : if str .find('+' ) >= 0 : return '+' elif str .find('-' ) >= 0 : return '-' elif str .find('*' ) >= 0 : return '*' elif str .find('/' ) >= 0 : return '/' elif str .find('%' ) >= 0 : return '%' else : return '**' calStr = raw_input('输入计算表达式,如a+b形式:' ) op = operator(calStr) num = calStr.split(op) print numres = 0.0 if op == '+' : res = float (num[0 ]) + float (num[1 ]) elif op == '-' : res = float (num[0 ]) - float (num[1 ]) elif op == '*' : res = float (num[0 ]) * float (num[1 ]) elif op == '/' : res = float (num[0 ]) / float (num[1 ]) elif op == '%' : res = int (num[0 ]) % int (num[1 ]) elif op == '**' : res = float (num[0 ]) ** float (num[1 ]) print 'result is %f' % str (res)
1 2 3 4 5 6 7 F = float (raw_input('输入温度:' )) C = (F-32 )*(5 /9.0 ) print '华氏度到摄氏度的转换后,结果为:' ,C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 print '0-20 之间的所有偶数:' i = 0 while i <= 20 : if (i % 2 == 0 ) : print i,' ' i += 1 print print '0-20 之间的所有奇数:' i = 0 while i <= 20 : if (i % 2 == 1 ) : print i,' ' i += 1 print a = int (raw_input('输入整数a:' )) b = int (raw_input('输入整数b:' )) if (a % b == 0 ): print 'a能被b整除' else : print 'a不能b整除'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def GCD (a, b ): '求a和b的最大公约数' if b == 0 : return a else : return GCD(b, a % b) def LCM (a, b ): '求a和b的最小公倍数' if (a * b == 0 ): return 0 else : return a * b / GCD(a,b) x = int (raw_input('输入x:' )) y = int (raw_input('输入y:' )) print 'GCD:' ,GCD(x, y)print 'LCM:' ,LCM(x, y)