核心编程答案(第二章)

2-10

1.使用try...ecxept来判断输入的是否为数字

#!/usr/bin/env python  
# encoding: utf-8  
  
while 1:  
    try:  
        a = float(raw_input('plz input a number:'))  
        if 1 <= a <=100:  
            print 'success!'  
            break  
        else:  
            print 'plz input a number between 1~100!'  
    except ValueError:  
        print 'What you input is not a numer!

2-11

1.用if语句来进行判断选择

#!/usr/bin/env python  
# encoding: utf-8  
import ipdb  
  
  
def to_average():  
    the_sum = 0  
    a = 0  
    for i in range(0, 5):  
        a = float(raw_input('plz input the %dst number:' % (i + 1)))  
        the_sum = the_sum + a  
        the_ave = the_sum / 5.0  
    print the_ave  
  
  
def to_sum():  
    the_sum = 0  
    a = 0  
    for i in range(0, 5):  
        a = float(raw_input('plz input the %dst number:' % (i + 1)))  
        the_sum = the_sum + a  
    print the_sum  
  
  
while 1:  
    a = raw_input('plz choose want you want and input the number("1:average, 2:sum, 3:exit"):')  
    if a == '1':  
        to_average()  
        break  
    elif a == '2':  
        to_sum()  
        break  
    elif a == '3':  
        break  
    else:  
        print 'plz input the number' 

2-15 两两比较,将最大(小)的放前面,如果有4个数,将会进行3+2+1=6次的比较

#!/usr/bin/env python
# encoding: utf-8

print "plz enter 3 number:"
num_1 = raw_input('num_1=')
num_2 = raw_input('num_2=')
num_3 = raw_input('num_3=')
num_4 = raw_input('num_4=')
if num_1 < num_2:
    num_1, num_2 = num_2, num_1
if num_1 < num_3:
    num_1, num_3 = num_3, num_1
if num_1 < num_4:
    num_1, num_4 = num_4, num_1
if num_2 < num_3:
    num_2, num_3 = num_3, num_2
if num_2 < num_4:
    num_2, num_4 = num_4, num_2
if num_3 < num_4:
    num_3, num_4 = num_4, num_3
print num_4, num_3, num_2, num_1

 

posted @ 2016-05-01 10:35  ohmydenzi  阅读(203)  评论(0编辑  收藏  举报