第十章

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

10-1 Python学习笔记 学习笔记 :在文本编辑器中新建一个文件,写几句话来总结一下你至此学到的Python知识,其中每一行都以“In Python you can”打头。将这个文件命名为 learning_python.txt,并将其存储到为完成本章练习而编写的程序所在的目录中。编写一个程序,它读取这个文件,并将你所写的内容打印三次:第一次打印时读取整个 文件;第二次打印时遍历文件对象;第三次打印时将各行存储在一个列表中,再在with 代码块外打印它们。 (以The Zen of Python 代替)
with open("The Zen of Python.txt") as file_object:
	contents = file_object.read()
	print(contents)

print()
with open("The Zen of Python.txt") as file_object:
	for line in file_object:
		print(line)

print()
with open("The Zen of Python.txt") as file_object:
	lines = file_object.readlines()

for line in lines:
	print(line,end = " ")
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.

Beautiful is better than ugly.

Explicit is better than implicit.

Simple is better than complex.

Beautiful is better than ugly.
 Explicit is better than implicit.
 Simple is better than complex. 
10-3 访客:编写一个程序,提示用户输入其名字;用户作出响应后,将其名字写入到文件guest.txt中。
with open("guest.txt","w") as file_object:
	name = input("Please input your name:")
	file_object.write(name)
Please input your name:Alice

guest.txt:
Alice
10-4 访客名单:编写一个while 循环,提示用户输入其名字。用户输入其名字后,在屏幕上打印一句问候语,并将一条访问记录添加到文件guest_book.txt中。确保这 个文件中的每条记录都独占一行。
with open("guest_book.txt","a") as file_object:
	name = input("Please input your name:")
	while name != "q":
		file_object.write(name + "\n")
		name = input("Please input your name:")
Please input your name:Alice
Please input your name:Bob
Please input your name:Ben
Please input your name:q

10-6 加法运算:提示用户提供数值输入时,常出现的一个问题是,用户提供的是文本而不是数字。在这种情况下,当你尝试将输入转换为整数时,将引 发TypeError 异常。编写一个程序,提示用户输入两个数字,再将它们相加并打印结果。在用户输入的任何一个值不是数字时都捕获TypeError 异常,并打印一条友好的错误消息。对你编写的程序进行测试:先输入两个数字,再输入一些文本而不是数字。
num1 = input("Please input the first integer:")
num2 = input("Please input the second integer:")
try:
	print(int(num1)+int(num2))
except TypeError:
	print("Please input the integers,NO other kinds of inputs.")
Please input the first integer:1
Please input the second integer:2
3
输入不是整数时,发现程序抛出的是ValueError,不是TypeError:
修改程序:

num1 = input("Please input the first integer:")
num2 = input("Please input the second integer:")
try:
	print(int(num1)+int(num2))
except ValueError:
	print("Please input the integers,NO other kinds of inputs.")
Please input the first integer:ze
Please input the second integer:5
Please input the integers,NO other kinds of inputs.





您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值