Python core programming 2 Chapter 5 after-school exercises, python after-school exercises

Source: Internet
Author: User
Tags integer division

Python core programming 2 Chapter 5 after-school exercises, python after-school exercises

I have used online materials for my own exercises. The accuracy is not guaranteed. Thank you for your advice:-D.

5-1 integer: differences between a common python integer and a long integer

Python has three types of integer types: Boolean, long, and standard. The difference between a common integer and a long integer is that the value range of the standard integer is-2 ^ 31 to 2 ^ 31-1. The value that a long integer can express is related to the memory of the machine.

5-2 defines a function used to multiply two numbers and call this function.

 #!/usr/bin/env pythondef Multiply(number1,number2):        return number1*number2if __name__=="__main__":        number1 =input("please enter the number1:")        number2 =input("please enter the number2:")        print Multiply(number1,number2)
5-3 standard operators. Write a script, enter a test score, and output the score based on the following criteria.

Score (A-F ).
A: 90-100
B: 80-89
C: 70-79
D: 60-69
F: <60

(The following script is recommended to add a judgment on the input data !!!!!)

#!/usr/bin/env pythondef score(number):        number=number/10        if number==9|number==10:                return 'A'        if number==8:                return 'B'        if number==7:                return 'C'        if number==6:                return 'D'        else:                return 'F'if __name__=="__main__":        number=input("please enter the number:")        print score(number)
  5-4 get the remainder. Determines whether a given year is a leap year. Use the following formula:
A leap year means that it can be divisible by 4, but cannot be divisible by 100, or it can be either 400 (I think it can be divisible by 4 and 100, in this way, the year 1900 is a leap year)
Division. For example, 1992,1996 and 2000 are leap years, But 1967 and 1900 are not leap years. Next is the entire world of a leap year.
July 2400.
#!/usr/bin/env pythondef isleapyear(year):        if (year%4==0 and year%100 !=0)or(year%4==0 and year%400==0):                return "%d is a leap year"%year        else:                return "%d is not a leap year"%yearif __name__=="__main__":        year=input("please enter the year:")        print isleapyear(year)
 

5-5 get the remainder. Take any amount less than $1 and calculate the minimum number of coins you can replace. There are four types of coins: 1 cent, 5 cents, 10 cents, and 25 cents. $1 equals 100 cents. For example, the Conversion Result of $0.76 is 3, 25, and 1, respectively. The results, like 76 items, 1 cent, 2 items, 25 cents, 2 items, 10 cents, 1 item, 5 cents, and 1 piece, all do not meet the requirements.

#!/usr/bin/env pythondef changecoin(number):    result=[]    meifen=[25,10,5]    for i in meifen:        result.append(number/i)        number=number%i    result.append(number)    return "25 Cent is %d,10 Cent is %d,5 Cent is %d,1 Cent is %d"%(result[0],result[1],result[2],result[3])if __name__=="__main__":        number=input("please enter the number:")        print changecoin(number)

5-6 counts. Write a computer program. Your code can accept this expression. two operands are added with an operator N1 operator N2. N1 and N2 are integer or floating point type, operators can be +,-, *,/, %, and *, indicating addition, subtraction, multiplication, integer division, remainder operation, and power operation respectively. Calculate the result of this expression and display it. Tip: You can use the string method split (), but you cannot use the built-in function eval ().

#!/usr/bin/env pythondef calculator(number1,i,number2):        if i=='+':                return number1+number2        if i=='-':                return number1-number2        if i=='*':                return number1*number2        if i=='/':                return number1/number2        if i=='%':                return number1%number2        if i=='**':                return number1**number2caozuo=['+','-','**','/','%','*']string =raw_input("please enter the string:")for obj in caozuo:        if string.find(obj)>-1 and string.count(obj)<2:                number =string.split(obj)                list =[]                for i in number:                        list.append(i)                number1=int(list[0])                i=obj                number2=int(list[1])print calculator(number1,i,number2)
5-7 business tax. Take a commodity amount at will, and then calculate the business tax payable based on the local business tax quota.
#!/usr/bin/env pythondef tax(number):        return number*0.8if __name__=="__main__":        number=input("Please enter the number:")        print tax(number)
  5-8 ry. Calculate the area and volume. (A) Square and cube (B) circles and balls
#!/usr/bin/env pythonimport mathdef Square_and_cube(length):        print "The area of the square is %d"%pow(length,2)        print "The volume of a cube is %d"%pow(length,3)def Circle_and_sphere(length):        print "The area of the Circle is %d"%pow(length,2)*math.pi        print "The volume of a sphere is %d"%pow(length,3)*math.pi*4/3 if __name__=="__main__":        print """        (1)Calculate square and cube        (2)Calculate Circle and sphere        (3)exit()        """        length=input("please enter the length:")        choice=input("please make the choice number:")        if choice==1:                Square_and_cube(length)        if choice==2:                Circle_and_sphere(length)        if choice==3:                exit
 

5-9. answer the following questions about the numerical format:
(A) Why is 17 + 32 equal to 49 in the following example, and 017 + 32 equal to 47,017 + 032 equal to 41?
 

17 + 32 are added as decimal values: 49

017 + 32: octal digit plus decimal digit: 15 + 32 = 47

017 + 032 are the sum of the two Octal numbers: 15 + 26 = 41

(B) Why is the result of the following expression 134L instead of 1342?
 

The numbers of two long integers are added together. l is similar to the number 1.

 

5-10 conversion. Write a pair of functions to convert degrees Fahrenheit to degrees Celsius. The conversion formula for C = (F-32) * (5/9) should use the true division in this exercise, otherwise you will get incorrect results

#!/usr/bin/env pythonfrom __future__ import divisiondef celcius(F):        C=F-32*(5/9)        return Cif __name__=="__main__":        F=input("please enter the Fahrenheit degree:")        print celcius(F)

 

5-11 get the remainder. (A) Use the loop and arithmetic operations to obtain 0 ~ All the even numbers between 20.
    #!/usr/bin/env python    for i in range(21):            if i%2==0:                    print i

 

(B) Same as above, but all odd numbers are output this time.
   #!/usr/bin/env python      for i in range(21):              if i%2==1:                      print i
(C) What is the simplest way to distinguish between odd and even numbers?
Check whether it can be divisible by 2
(D) Use the result of (c) to write a function to check whether an integer is divisible by another integer. First, the user is required to enter two numbers. Then, your function determines whether there is a division relationship between the two, and returns True and False based on the judgment results.
#!/usr/bin/env pythondef div(num1,num2):        if num1%num2==0:                return "True"        else:                return "False"if __name__=="__main__":        num1=input("please type the num1:")        num2=input("please type the num2:")        print "%d divided %d is %s"%(num1,num2,div(num1,num2))

5-12 system restrictions. Write a script to check the integer, long integer, floating point, and plural range that your Python can process.

Print sys. maxint

Print-sys. maxint-1

Print sys. float_info

Print sys. long_info

 

5-13 Conversion. Write a function to convert the time represented by hours and minutes to the time represented by minutes.

#!/usr/bin/env pythondef time(h,t):        h=int(h)        t=int(t)        t=h*60+t        print "The minutes is",tif __name__=="__main__":        s=raw_input("please input the time in HH:MM...\n")        s=s.split(":")        time(s[0],s[1])
 

5-14 bank interest. Write a function with the time deposit rate as the parameter. If the account calculates compound interest on a daily basis, calculate the return rate on a yearly basis.

#!/usr/bin/env pythonday_rate=float(raw_input("please type the day rate:\n"))year_rate=(1+day_rate)**365-1print "Annual return is %f"%year_rate
 

5-15: maximum common divisor and least common multiple. Calculate the maximum common divisor and least common multiple of two integer types.

#!/usr/bin/env pythondef gcd(num1,num2):        i=1        while True:                i+=1                if (i%num1==0)&(i%num2==0):                        break        return "the gcd is %d"%idef lcm(num1,num2):        i=max(num1,num2)        while True:                i-=1                if (num1%i==0)&(num2%i==0):                        break        return "the lcm is %d"%iif __name__=="__main__":        num1=input("please enter the number1:")        num2=input("please enter the number2:")        print gcd(num1,num2)        print lcm(num1,num2)
  5-16 families. Specify an initial amount and monthly overhead, and use a cycle to determine the remaining amount and the number of expenditures in the current month, including the final expenditure. The Payment () function uses the initial amount and monthly quota. The output result is similar to the following format (the numbers in the column are only used for demonstration ).Enter opening balance: 100.00 Enter monthly payment: 16.13 Amount RemainingPymt # Paid Balance ----- ------ --------- 0 $0.00 $100.001 $16.13 $83.872 $16.13 $67.743 $16.13 $51.614 $16.13 $35.485 $16.13 $19.356 $0.00
#!/usr/bin/env pythondef pay(paid,balance):  print "Pymt# Paid Balance"  print "----- ----- ------"  i=0  b=balance  while(balance>paid):    balance=balance - paid    i+=1    print " %d $%f $%f"%(i,paid,balance)    i+=1    print" %d $%f $%f"%(i,balance,0)if __name__=="__main__":  balance=raw_input("please enter the balance:")  paid=raw_input("please enter the paid:")  balance=float(balance)  paid=float(paid)  pay(paid,balance)

 

 

 

A random number ranging from 5 to 17. Familiar with the random number module and then solve the following question: generate a list of N elements consisting of n random numbers. The values of N and n are as follows: (1 <N <= 100), (0 <= n <= 231-1 ). Then, the number of N (1 <= N <= 100) in the list is randomly obtained, sorted, and the subset is displayed.

#!/usr/bin/pythonimport randomnum = random.randint(1,100)lst=[]for item in range(num):        tmp = random.randint(0,(pow(2,31)-1))        lst.append(tmp)lst.sort()print lst

 


What is the focus of python learning? With the second version of python core programming, how can this book be used better?

Python is the fourth-generation programming language. It has a low entry threshold and a quick start.
At the beginning, to cultivate interest, you can write some small script examples, such as batch file processing and regular expression matching;
Other network applications can also be involved.
To be more in-depth, you need to understand object-oriented.
The core programming book is a collection of online python Forum results, more practical, you can learn from examples.
Then you can look for popular python frameworks and python open-source projects to see the source code.
But in general, python has a bottleneck in efficiency. Generally, it plays the role of script cohesion and batch processing in large systems.

How does Python core programming (version 2)

Upstairs nonsense. The second version was revised for the first version because of the upgrade of the python version. This book is suitable for beginners and detailed in the basic part.
It is recommended to install python, which can be learned and tested.
This book is intended for python2.5 and should never contain 3.1

Don't buy it. If you have a computer, just go to the next pdf.

Related Article

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.