python学习笔记-day5
1.输入与输出
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input("Enter text: ")
if is_palindrome(something):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
2.文件
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:use Python!
'''
f = open('poem.txt', 'w')
f.write(poem)
f.close()
f = open('poem.txt')while True:
line = f.readline()
if len(line) == 0:
break
print(line, end='')
f.close()
输出:
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!
print(line, end=''):打印读取到的行。end=''参数确保打印时不添加额外的换行符,因为readline()已经包含了行末的换行符。
在默认情况下, open() 会将文件视作文本(text)文件,并以阅读(read)模式打开它。
3.处理异常
finally块中的代码无论是否发生异常都会执行,通常用于资源的释放,如关闭文件、断开网络连接等。
with
此外,with 语句确保文件在使用完毕后会自动关闭,不需要手动关闭文件。
with open("poem.txt") as f:
这行代码使用 with 语句和 open 函数打开名为 "poem.txt" 的文件。
5.标准库
日志
6.传递元组