File and unusual exercises 2 - PYTHON programming from entry to practice

Adder 10-6: prompt the user for input values ​​is provided, a problem often occurs that the user-provided text rather than numbers. In this case, when you try to enter into an integer, TypeError exception is thrown. Write a program that prompts the user for two numbers, then add them up and print the results. When any one of the numeric value entered by the user are captured TypeError exception and print a friendly error messages. Procedures for the preparation of this test: Enter two numbers, enter some text rather than numbers.

[url=][/url]
print("Enter two numbers, and I'll add them.")first_number = input("\nFirst number: ")second_number = input("Second number: ")try:    nums_sum = int(first_number) + int(second_number)    print(first_number + '+' + second_number + '=' + str(nums_sum))except ValueError:    print("Sorry! Only accept numbers input.")[url=][/url]

Addition calculator 10-7: 10-6 of the code in a while loop, allowing users to make mistakes (input text instead of a number of) after can continue to enter numbers.

[url=][/url]
print("Enter two numbers, and I'll add them.")print("Enter 'q' to quit.")while True:    first_number = input("\nFirst number: ")    if first_number == 'q':        break    second_number = input("Second number: ")    if second_number == 'q':        break    try:        nums_sum = int(first_number) + int(second_number)        print(first_number + '+' + second_number + '=' + str(nums_sum))    except ValueError:        print("Sorry! Only accept numbers input.")[url=][/url]

10-8 cats and dogs: creates two files cats.txt and dogs.txt, stores at least three cats in the name of the first file and the second file name stored in at least three dogs. Write a program that tries to read these documents, and print its contents to the screen. These code in a try-except block in order to catch errors FileNotFound file does not exist, and a print-friendly message. Wherein a file transfer to another place, and except confirm correct execution code block.

[url=][/url]
file_names = ['cats.txt', 'dogs.txt']for filename in file_names:    try:        with open(filename) as f_obj:            names = f_obj.read()            print(filename + " include:\n" + names.rstrip())    except FileNotFoundError:        print("Sorry, the file " + filename + " can not fond.")[url=]

 

[/url]

10-9 silent cats and dogs: Modify the code block 10-8, so that the program file without saying a word does not exist.

[url=]

 

[/url]
file_names = ['cats.txt', 'dogs.txt']for filename in file_names:    try:        with open(filename) as f_obj:            names = f_obj.read()            print(filename + " include:\n" + names.rstrip())    except FileNotFoundError:        pass[url=]

 

[/ url]
more technical information may concern: gzitcast

Guess you like

Origin www.cnblogs.com/heimaguangzhou/p/11775083.html