Learn Python the Hard Way -- ex17-ex18

ex17:

今天又想了一下ex17的内容,open(from_file)这个命令的结果赋给in_file,这个应该是给什么样的东西都可以,修改代码验证了一下,果然可行。之前的想法应该是正确的,input作为一个python固有的命令,不能用作参数名(变量?)

from sys import argv
from os.path import exists 

script, from_file, to_file = argv 

print ("Copying from %s to %s" %(from_file, to_file)) 

# we could do these two on one line, how?
file1 = open(from_file)  #把in_file改成file1也没有问题
indata = file1.read() 
#indata= open(from_file).read() #上面的两句命令可以通过这样的一个命令写成一句


print ("The input file is %d bytes long" %len(indata)) 

print ("Does the output file exist? %r" %exists (to_file))
print ("Ready, hit RETURN to continue, CTRL-C to abort.")
input() 

output = open(to_file, 'w')
output.write(indata) 

print("Alright, all done.") 

output.close()
file1.close() 
#open(from_file).close() 若上面的命令写成了一句最后一句要变成这样

后续习题有将此脚本改短一点,最后修改后命令如下,运行成功。

from sys import argv

script, from_file, to_file=argv

open(to_file,'w').write(open(from_file).read())

ex18 定义函数,代码如下:

# this one is like your scripts with argv
def print_two(*args):
	arg1, arg2=args
	print ("arg1: %r, arg2: %r" %(arg1, arg2))
	
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2): #跳过参数解包的过程,直接使用()里边的名称作为变量名
	print("arg1:%r, arg2: %r" %(arg1,arg2))
	
# this just takes one argument
def print_one(arg1):
	print("arg1 :%r" %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()

写函数注意事项总结:

  1. 函数定义以def开始;
  2. 函数名称以姿俯和下划线_组成;
  3. 函数名称后面紧跟着括号;
  4. 括号里包含参数的话,多个参数要以逗号隔开;
  5. 参数名称不能有重复;
  6. 紧跟着参数的要是“):”;
  7. 紧跟着函数定义的代码要有四个空格的缩进(indent);
  8. 函数结束的位置要取消缩进(dedent)
  9. 调用函数时要使用函数名称。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值