码迷,mamicode.com
首页 > 其他好文 > 详细

核心编程答案(第二章)

时间:2016-05-01 11:02:37      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

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

 

核心编程答案(第二章)

标签:

原文地址:http://www.cnblogs.com/ohmydenzi/p/5450140.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!