Core programming answers (chap. II)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.