习题11——提问
源代码:
print("How old are you?", end=' ')
age = input()
print("How tall are you?", end=' ')
height = input()
print("How much do you weight?", end=' ')
weight = input()
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
运行结果:
How old are you? 30 How tall are you? 172cm How much do you weight? 65kg So, you're 30 old, 172cm tall and 65kg heavy.
习题12——提示别人
源代码:
age = input("How old are you? ")
height = input("How tall are you? ")
weight = input("How much do you weigh? ")
print(f"So, you're {age} old, {height} tall and {weight} heavy.")
运行结果:
How old are you? 30 How tall are you? 172cm How much do you weigh? 65kg So, you're 30 old, 172cm tall and 65kg heavy.
习题13——参数、解包和变量
源代码:
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
运行结果:
ValueError Traceback (most recent call last) Input In [8], in <cell line: 3>() 1 from sys import argv 2 # read the WYSS section for how to run this ----> 3 script, first, second, third = argv 5 print("The script is called:", script) 6 print("Your first variable is:", first) ValueError: not enough values to unpack (expected 4, got 3)
注意需在终端运行并传入参数
习题14——提示和传递
源代码:
from sys import argv
script, user_name = argv
prompt = '> '
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.
And you have a {computer} computer. Nice.
""")
运行结果:
1deMacBook-Pro:data-python a1$ python test.py Ken
Hi Ken, I'm the test.py script.
I'd like to ask you a few questions.
Do you like me Ken?
> yes
Where do you live Ken?
> chengdu
What kind of computer do you have?
> macbookpro
Alright, so you said yes about liking me.
You live in chengdu. Not sure where that is.
And you have a macbookpro computer. Nice.
习题15——读取文件
源代码:
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here's your file {filename}:")
print(txt.read())
print("Type the filename again:")
file_again = input("> ")
txt_again = open(file_again)
print(txt_again.read())
运行结果:
1deMacBook-Pro:data-python a1$ python3 test.py 1.txt
Here's your file 1.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
> 1.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
注:要在终端中运行,且需要提前创建好待打开的文件