习题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.
注:要在终端中运行,且需要提前创建好待打开的文件
习题16——读写文件
源代码:
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL~C.")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename,'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()
运行结果:
data-python a1$ python3 ex16.py test.txt
We're going to erase test.txt.
If you don't want that, hit CTRL~C.
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: 1
line 2: 2
line 3: 3
I'm going to write these to the file.
And finally, we close it.
习题17——更多文件操作
源代码:
from sys import argv
from os.path import exists
script, from file, to_file = argv
print(f"Copying from {from_file} to {to_file}")
in_file = open(from_file)
indata = in_file.read()
print(f"The input file is {len(indata)} bytes long")
print(f"Dose the output file exists? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL_C to abort.")
input()
out_file = open(to_file, 'w')
out_file.write(indata)
print("Alright, all done.")
out_file.close()
in_file.close()
运行结果:
data-python a1$ python3 ex17.py 2.txt test.txt
Copying from 2.txt to test.txt
The input file is 29 bytes long
Dose the output file exists? True
Ready, hit RETURN to continue, CTRL_C to abort.
习题18——命名、变量、代码和函数
源代码:
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print(f"arg1: {arg1}, arg2: {arg2}")
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print(f"arg1: {arg1}, arg2: {arg2}")
# this just takes one argument
def print_one(arg1):
print(f"arg1: {arg1}")
# this one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
运行结果:
arg1: Zed, arg2: Shaw arg1: Zed, arg2: Shaw arg1: First! I got nothin'.
习题19——函数和变量
源代码:
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses!")
print(f"You hanve {boxes_of_crackers} boxes of crackers!")
print("Man that's enough for a partty!")
print("Get a blanker.\n")
print("We can just give the function numbers directly:")
cheese_and_crackers(20, 30)
print("OR, we can use variables from our script:")
amount_of_cheese = 10
amount_of_crackers = 50
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
print("We can even do math inside too:")
cheese_and_crackers(10 + 20, 5 + 6)
print("And we can combine the two, variables and math:")
cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
运行结果:
We can just give the function numbers directly: You have 20 cheeses! You hanve 30 boxes of crackers! Man that's enough for a partty! Get a blanker. OR, we can use variables from our script: You have 10 cheeses! You hanve 50 boxes of crackers! Man that's enough for a partty! Get a blanker. We can even do math inside too: You have 30 cheeses! You hanve 11 boxes of crackers! Man that's enough for a partty! Get a blanker. And we can combine the two, variables and math: You have 110 cheeses! You hanve 1050 boxes of crackers! Man that's enough for a partty! Get a blanker.
习题20——函数和文件
源代码:
from sys import argv
script, input_file = argv
def print_all(f):
print(f.read())
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print(line_count, f.readline())
current_file = open(input_file)
print("First let's print the whole file:\n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")
rewind(current_file)
print("Let's print three lines:")
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
运行结果:
First let's print the whole file:
Hello
How are you
Fine thanks
Now let's rewind, kind of like a tape.
Let's print three lines:
1 Hello
2 How are you
3 Fine thanks