习题14
from sys import argv
script, user_name, age = argv
prompt = "Your answer: "
print(f"Hi {user_name}, I'm the {script} script.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
print(f"Where do you live {user_name}?")
lives = input(prompt)
print("What kind of computer do you have?")
computer = input(prompt)
print(f"""
Alright, so you said {likes} about liking me.
You live in {lives}. Not sure where that is.
You are {age} years old now.
And you have a {computer} computer. Nice.
""")
PS D:\pythonp> python .\ex14.py h 24
Hi h, I'm the .\ex14.py script.
I'd like to ask you a few questions.
Do you like me h?
Your answer: y
Where do you live h?
Your answer: C
What kind of computer do you have?
Your answer: m
Alright, so you said y about liking me.
You live in C. Not sure where that is.
You are 24 years old now.
And you have a m computer. Nice.
习题15 读取文件
# 将sys模块导入
from sys import argv
# 将argv解包,将所有的参数依次赋值给左边的变量
script, filename = argv
# 打开filename文件,并将该文件赋值给txt
txt = open(filename)
# 打印格式化字符串,“这是你的文件xxx:”
print(f"Here's your file {filename}:")
# 读取并打印txt的全部内容
print(txt.read())
# 打印“再次输入文件名”
print("Type the filename again")
# 打印“>”符号,并将输入的内容赋值给file_again
file_again = input(">")
# 打开file_again文件,并将文件赋值给txt_again
txt_again = open(file_again)
# 读取并打印txt_again的全部内容
print(txt_again.read())
ex15_sample.txt内容
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
输出结果
PS D:\pythonp> python ex15.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
Type the filename again
>ex15_sample.txt
This is stuff I typed into a file.
It is really a cool stuff.
Lots and lots fun to have in here.
- 删掉第10~15行用到 input的部分,再运行一遍脚本。
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())