您的位置:首页 > 编程语言 > Python开发

高级编程技术(Python)作业10

2018-04-08 17:16 375 查看
10-2 C语言学习笔记:可使用方法replace()将字符串中的特定单词都替换为另一个单词。下面是一个简单的示例,演示了如何将句子中的’dog’ 替换为’cat’:

>>> message = "I really like dogs."
>>> message.replace('dog', 'cat')
'I really like cats.'


读取你刚创建的文件learning_python.txt中的每一行,将其中的Python都替换为另一门语言的名称,如C。将修改后的各行都打印到屏幕上。

Solution:

filename = 'learning_python.txt'

with open(filename) as file_object:
contents = file_object.read()
message = contents.replace('Python', 'C')
print(message)


Output:

In C you can open a file.
In C you can close a file.


10-7 加法计算器:将你为完成练习10-6而编写的代码放在一个while循环中,让用户犯错(输入的是文本而不是数字)后能够继续输入数字。

Solution:

while(1):
print("Please enter 2 numbers, and I will add them.")
print("Enter q to quit.")

first_number = input("\n First number: ")
if first_number == 'q':
break
second_number = input("\n Second number: ")
if second_number == 'q':
break

try:
answer = int(first_number) + int(second_number)
except ValueError:
print("You should input numbers!")
else:
print(answer)


Output:

Please enter 2 numbers, and I will add them.
Enter q to quit.

First number: dsfsa

Second number: sadfsda
You should input numbers!

Please enter 2 numbers, and I will add them.
Enter q to quit.

First number: 1

Second number: 1
2
Please enter 2 numbers, and I will add them.
Enter q to quit.

First number: quit

Second number: q


10-13 验证用户:最后一个remember_me.py版本假设用户要么已输入其用户名,要么是首次运行该程序。我们应修改这个程序,以应对这样的情形:当前和最后一次运行该程序的用户并非同一个人。

为此,在greet_user() 中打印欢迎用户回来的消息前,先询问他用户名是否是对的。如果不对,就调用get_new_username()让用户输入正确的用户名。

Solution:

import json

def get_stored_username():
"""Get stored username if available."""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username

def get_new_username():
"""Prompt for a new username."""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username

def greet_user():
"""Greet the user by name."""
username = get_stored_username()
if username:
response = input("Is " + username + " your name? Y/N ")
if response == 'Y':
print("Welcome back, " + username + "!")
elif response == 'N':
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")
else:
print("Wrong input!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")

greet_user()


Output of the first time:

What is your name? ashero
We'll remember you when you come back, ashero!


Output of the second time:

Is ashero your name? Y/N N
What is your name? faker
We'll remember you when you come back, faker!


Output of the third time:

Is faker your name? Y/N Y
Welcome back, faker!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: