Python习题——2018-04-04作业

10-4 访客名单:编写一个while循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这个文件中的每条记录都独占一行。

filename = 'guest_book.txt'

with open(filename, 'a') as file_object:
    while True:
        name = input("What is your name? (enter 'q' to quit) ")
        if name == 'q':
            break
        print('Hello, ' + name.title() + '!')
        file_object.write(name + '\n')

输入:

Alice
Bob
q

输出:

What is your name? (enter 'q' to quit) Alice
Hello, Alice!
What is your name? (enter 'q' to quit) Bob
Hello, Bob!
What is your name? (enter 'q' to quit) q

guest_book.txt

Alice
Bob

 
10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引发TypeError异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
10-7 加法计算器:将你为完成练习10-6而编写的代码放在一个while循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

while True:
    nums = input("Please enter two numbers (enter 'q' to exit): ")
    if nums == 'q':
        break
    try:
        num_list = [int(num) for num in nums.split()]
    except ValueError:
    # 个人理解是题目出错了,nums类型是字符串并没有错,应为ValueError.
        print("Sorry, please enter numbers.\n")
    else:
        msg = 'The result of adding the two numbers is: '
        print(msg + str(num_list[0] + num_list[1]) + '\n')

输入:

233 666
hello, world
123 321
q

输出:

Please enter two numbers (enter 'q' to exit): 233 666
The result of adding the two numbers is: 899

Please enter two numbers (enter 'q' to exit): hello, world
Sorry, please enter numbers.

Please enter two numbers (enter 'q' to exit): 123 321
The result of adding the two numbers is: 444

Please enter two numbers (enter 'q' to exit): q

 
10-11 喜欢的数字:编写一个程序,提示用户输入他喜欢的数字,并使用json.dump()将这个数字存储到文件中。再编写一个程序,从文件中读取这个值,并打印消息“I know your favorite number! It’s _____.”。
10-12 记住喜欢的数字:将练习10-11中的两个程序合而为一。如果存储了用户喜欢的数字,就向用户显示它,否则提示用户输入他喜欢的数字并将其存储到文件中。运行这个程序两次,看看它是否像预期的那样工作。

import json

filename = 'favorite_numbers.json'
try:
    with open(filename) as f_obj:
        favorite_number = json.load(f_obj)
except FileNotFoundError:
    with open(filename, 'w') as f_obj:
        favorite_numbers = int(input('What is your favorite number? '))
        json.dump(favorite_numbers, f_obj)
else:
    print("I know your favorite number! It's " + 
            str(favorite_number) + '.')

输入:(程序运行了两次,只在第一次需要输入)

666

输出:(程序运行两次的结果)

What is your favorite number? 666
I know your favorite number! It's 666.

favorite_numbers.json

666

猜你喜欢

转载自blog.csdn.net/Draymond_666/article/details/79822862