2-10
1. Use try...ecxept to determine if the input is a number
#!/usr/bin/env python#Encoding:utf-8 while1: Try: A= Float (Raw_input ('plz input a number:')) if1 <= a <=100: Print 'success!' Break Else: Print 'plz input A number between 1~100!' exceptValueError:Print 'What are you input are not a numer!
2-11
1. Use the IF statement to determine the selection
#!/usr/bin/env python#Encoding:utf-8Importipdbdefto_average (): The_sum=0 A=0 forIinchRange (0, 5): A= Float (Raw_input ('plz input the%dst number:'% (i + 1))) The_sum= The_sum +a the_ave= the_sum/5.0PrintThe_avedefto_sum (): The_sum=0 A=0 forIinchRange (0, 5): A= Float (Raw_input ('plz input the%dst number:'% (i + 1))) The_sum= The_sum +aPrintThe_sum while1: A= Raw_input ('plz choose want you want and input the number ("1:average, 2:sum, 3:exit"):') ifA = ='1': To_average () Break elifA = ='2': To_sum () Break elifA = ='3': Break Else: Print 'plz input the number'
2-15 22 comparison, will be the largest (small) put in front, if there are 4 numbers, will be performed 3+2+1=6 times comparison
#!/usr/bin/env python#Encoding:utf-8Print "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=')ifNum_1 <num_2:num_1, Num_2=num_2, Num_1ifNum_1 <num_3:num_1, Num_3=Num_3, Num_1ifNum_1 <num_4:num_1, Num_4=Num_4, Num_1ifNum_2 <num_3:num_2, Num_3=Num_3, Num_2ifNum_2 <num_4:num_2, Num_4=Num_4, Num_2ifNum_3 <Num_4:num_3, Num_4=Num_4, Num_3PrintNum_4, Num_3, Num_2, num_1
Core programming answers (chap. II)