pi_string = '' for line in lines: pi_string += line.strip()
birthday = input("Enter your birthday, in the form mmddyy:") if birthday in pi_string: print("Your birthday appears in the first million digits of pi!") else: print("Your birthday does not appear in the first million digits of pi.")
Enter your birthday, in the form mmddyy: 040413
Your birthday does not appear in the first million digits of pi.
写入文件
读取模式r、写入模式w、附加模式a或让你能够读取和写入文件的模式r+
1 2 3 4
filename = 'programming.txt'
withopen(filename, 'w') as file_object: file_object.write("I love programming.")
异常
异常合集Expection 万物皆可用
处理ZeroDivisionError异常
1
print(5/0)
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[13], line 1
----> 1 print(5/0)
ZeroDivisionError: division by zero
使用try-except代码块
1 2 3 4
try: print(5/0) except ZeroDivisionError: print("You can't divide by zero!")
You can't divide by zero!
else 代码块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.")
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: 5
Second number: 2
The result is: 2.5
First number: q
分析文本
1 2
title = "Alice in Wonderland" title.split()
['Alice', 'in', 'Wonderland']
1 2 3 4 5 6 7 8 9 10 11 12
file_name = 'alice1.txt'
try: withopen(file_name) as f: contents = f.read() except FileNotFoundError: msg = "Sorry, the file " + file_name + " does not exist." print(msg) else: words = contents.split() num_words = len(words) print(f"The file {file_name} has about {str(num_words)} words.")
Sorry, the file alice1.txt does not exist.
1 2 3 4 5 6 7 8 9 10 11 12
file_name = 'alice.txt'
try: withopen(file_name, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: msg = "Sorry, the file " + file_name + " does not exist." print(msg) else: words = contents.split() num_words = len(words) print(f"The file {file_name} has about {str(num_words)} words.")
The file alice.txt has about 17868 words.
失败时一声不吭pass
1 2 3 4 5 6 7 8 9 10 11
file_name = 'alice1.txt'
try: withopen(file_name) as f: contents = f.read() except FileNotFoundError: pass else: words = contents.split() num_words = len(words) print(f"The file {file_name} has about {str(num_words)} words.")