Python教材第十章部分习题

教材:《Python编程 从入门到实践》

10-3:访客

#10-3 visitor
with open("visitor.txt", "w") as writer:
    print("Please enter your name:")
    name = input()
    writer.write(name)
print("File successfully written")

运行程序后根据提示输入名字后,可见当前目录下的visitor.txt文件中出现了刚刚输入的名字。

10-4:访客名单

#10-4 visitors
with open("visitors.txt", "w") as writer:
    while True:
        print("Please enter your name:")
        name = input()
        if name == 'q':
            break
        writer.write(name + '\n')
        print("welcome, " + name)
print("File successfully written")

每输入一个名字会看到一句欢迎信息,输入'q'结束,文件中可见每个名字占了一行。

10-6:加法运算

#10-6 addition
print("please input two integers one by one:")
try:
    a = int(input())
    b = int(input())
except ValueError:
    print("That's not an integer!")
else:
    print(a + b)

输入1和2时的命令行显示:

please input two integers one by one:
1
2
3

输入一个字母时的显示:

please input two integers one by one:
a
That's not an integer!






猜你喜欢

转载自blog.csdn.net/qq_35783731/article/details/79830921