文档章节

笨方法学python III

渺渺星辰
 渺渺星辰
发布于 2017/07/17 17:06
字数 3092
阅读 57
收藏 0

17.笨办法学 Python-第十七题

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第十七题
#通过文件操作对文件进行复制
from sys import argv
import os
from os.path import exists
# 给出文件的名称
script,from_file,to_file=argv
print 'coping from %s to %s' %(from_file,to_file)
#打开要复制的文件
Ffile=open('./15_sample.txt')
#读取要复制的文件
indata=Ffile.read()
#查看复制内容的长度
print "the input file is %d bytes long " % len(indata)
#判断是否有这个文件
print "dose the output file exits %r" %exists(to_file)

Tfile = open(to_file, 'w+')

#写入要复制的内容
Tfile.write(indata)
# 关闭文件
Tfile.close()
Ffile.close()

知识点:复制文件内容到另外一个文件,exists命令将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False

运行结果:

执行语句: python 17.py 15_sample.txt 17_sample.txt

coping from 15_sample.txt to 17_sample.txt
the input file is 18 bytes long 
dose the output file exits True

18.笨办法学 Python-第十八题

函数可以做三样事情:
1. 它们给代码片段命名,就跟“变量”给字符串和数字命名一样。
2. 它们可以接受参数,就跟你的脚本接受 argv 一样。
3. 通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”
 

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第十八题
#命名,变量,代码,函数
#函数
def print_two(*args):
    arg1,arg2=args
    print 'arg1: %r,arg2:%r' %(arg1,arg2)
#跳过整个参数解包的过程,直接使用 () 里边的名称作为变量名
def again_print_two(arg1,arg2):
    print "arg1=%r,arg2=%r" %(arg1,arg2)
# 函数如何接受单个参数
def print_arg1(arg1):
    print 'arg1:',str(arg1)
#函数可以不接收任何参数
def print_noth():
    print 'nothing'

print_two(1,2)
print_arg1(560)
again_print_two('wang','zhen')

知识点:

函数的执行流程:

1. 首先告诉 Python 创建一个函数,我们使用到的命令是 def ,也就是“定义(define)”的意思。
2. 紧接着 def 的是函数的名称。本例中它的名称是 “print_two”,但名字可以随便取,就叫 “peanuts” 也没关系。但最好函数的名称能够体现出函数的功能来。
函数名称是以字符和下划线 _ 组成
3. 然后我们告诉函数我们需要 *args (asterisk args),这和脚本的 argv 非常相似,参数必须放在圆括号 () 中才能正常工作。
4. 接着我们用冒号 : 结束本行,然后开始下一行缩进。
5. 冒号以下,使用 4 个空格缩进的行都是属于 print_two 这个函数的内容。 其中第一行的作用是将参数解包,这和脚本参数解包的原理差不多。
6. 为了演示它的工作原理,我们把解包后的每个参数都打印出来,这和我们在之前脚本练习中所作的类似。

 

执行结果:

arg1: 1,arg2:2
arg1: 560
arg1='wang',arg2='zhen'

函数定义过程中注意事项:

1. 函数定义是以 def 开始的吗?
2. 函数名称是以字符和下划线 _ 组成的吗?
3. 函数名称是不是紧跟着括号 ( ?
4. 括号里是否包含参数?多个参数是否以逗号隔开?
5. 参数名称是否有重复?(不能使用重复的参数名)
6. 紧跟着参数的是不是括号和冒号 ): ?
7. 紧跟着函数定义的代码是否使用了 4 个空格的缩进 (indent)?
8. 函数结束的位置是否取消了缩进 (“dedent”)?

 

运行时候注意事项:

1. 调运函数时是否使用了函数的名称?
2. 函数名称是否紧跟着 ( ?
3. 括号后有无参数?多个参数是否以逗号隔开?
4. 函数是否以 ) 结尾?

 

19.笨办法学 Python-第十九题

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第十九题
def chese_and_crackers(cheese_count,boxes_of_crackers):
    print 'you have %d cheeses!' % cheese_count
    print 'you have %d boxes of crackers!' % boxes_of_crackers
    print "man that is enough for a party"
    print 'get a blanket!'

print '第一种方法----->we can just give the function numbers directly:'

chese_and_crackers(20,30)

print '第二种方法---->or,we can use variable from our script:'
amount_of_cheese=10
amount_of_crackers=50
chese_and_crackers(amount_of_cheese,amount_of_crackers)

print '第三种方法---->we can even do math inside too:'
chese_and_crackers(10+20,5+6)

print '第四种方法---->we can combine the two,variables and math:'
chese_and_crackers(amount_of_cheese+100,amount_of_crackers+1000)

知识点:使用不同的方法给函数进行传参a.直接赋值b.使用变量c.使用数学计算,d使用变量的运算

运行结果:

第一种方法----->we can just give the function numbers directly:
you have 20 cheeses!
you have 30 boxes of crackers!
man that is enough for a party
get a blanket!
第二种方法---->or,we can use variable from our script:
you have 10 cheeses!
you have 50 boxes of crackers!
man that is enough for a party
get a blanket!
第三种方法---->we can even do math inside too:
you have 30 cheeses!
you have 11 boxes of crackers!
man that is enough for a party
get a blanket!
第四种方法---->we can combine the two,variables and math:
you have 110 cheeses!
you have 1050 boxes of crackers!
man that is enough for a party
get a blanket!

 

20.笨办法学 Python-第二十题

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第二十题
#函数和文件结合
from sys import argv
script,file=argv
#读取文件内容
def read(f):
    print f.read()
#指针回到开头
def rewind(f):
    f.seek(0,0)
#读取一行文件内容
def read_a_line(line_count,f):
    print line_count,f.readline()
#关闭文件
def close(f):
    f.close()

current_file=open(file)
print 'read all file:'
read(current_file)

print '指针回到开头完成!'
rewind(current_file)

current_line=1
print '打印出一行的内容:'
read_a_line(current_line,current_file)
print '打印出二行的内容:'
current_line+=1
read_a_line(current_line,current_file)
print '打印出三行的内容:'
current_line+=1
read_a_line(current_line,current_file)

print '关闭文件'
close(current_file)

知识点: 结合文件的处理使用函数的进行定义

执行结果:

执行语句:python 20.py 15_sample.txt

read all file:
line1
line2
line3

指针回到开头完成!
打印出一行的内容:
1 line1

打印出二行的内容:
2 line2

打印出三行的内容:
3 line3

关闭文件
 

21.笨办法学 Python-第二十一题

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第二十一题
#函数有返回值的
print "简单的四则运算:"
def add(a,b):
    return a+b
def subtract(a,b):
    return a-b
def multiply(a,b):
    return a*b
def divide(a,b):
    return a/b

age=add(30,5)
height=subtract(78,4)
weight=multiply(90,2)
iq=divide(100,2)

print 'age:%d,height:%d,weight:%d,iq:%d'%(age,height,weight,iq)

what = add(age, subtract(height, multiply(weight, divide(iq,2))))

print what

知识点: 有返回值的函数

执行历程:

1. 调用函数时使用了两个参数: a 和 b 。
2. 打印出这个函数的功能,这里就是计算加法(adding)
3. 接下来我们告诉 Python 让它做某个回传的动作:将 a + b 的值返回(return)。或者这么说:“将 a 和 b 加起来,再把结果返回。”
4. Python 将两个数字相加,然后当函数结束的时候,它就可以将 a + b 的结果赋予一个变量。

 

运行结果:

简单的四则运算:
age:35,height:74,weight:180,iq:50
-4391

22/23.笨办法学 Python-第二十二和二十三题

自主学习python其他的符号标识符,去网上查看python相关文件

查看python代码的网址: bitbucket.org,github.com,launchpad.net,koders.com

 

24.笨办法学 Python-第二十四

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第二十四题
#针对前面的知识的复习和总结

print 'let us practice everything'

print 'you\'d need to konw \'bout escapes with \\ that do \n newline and \t tabs'

poem='''
\tThe Zen of Python, by Tim Peters\n
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''

print '==================================='
print poem
print '==================================='

five=10-2+3-6
print 'this should be five: %d'  %five

def secret_formula(started):
    jelly_beans=started*500
    jars=jelly_beans/1000
    crates=jars/100
    return jelly_beans,jars,crates
start_point=1000
beans,jars,crates=secret_formula(start_point)

print 'with a starting point of : %d' %start_point
print 'we have %d beans,%d jars, and %d crates.'%(beans,jars,crates)

start_point/=10
print 'we have %d beans,%d jars, and %d crates.' %secret_formula(start_point)

 

知识点:复习学过的知识

运行结果:

let us practice everything
you'd need to konw 'bout escapes with \ that do 
 newline and      tabs
===================================

    The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

===================================
this should be five: 5
with a starting point of : 1000
we have 500000 beans,500 jars, and 5 crates.
we have 50000 beans,50 jars, and 0 crates.

 

25.笨办法学 Python-第二十五

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第二十五题
#针对前面的知识的复习和总结
def break_words(stuff):
    words=stuff.split()
    return words
def sort_words(words):
    return sorted(words)
def print_frist_word(words):
    word=words.pop(0)
    print word
def print_last_word(words):
    word=words.pop(-1)
    print word
def sort_sentence(sentence):
    words=break_words(sentence)
    return sort_words(words)
def print_frist_and_last(sentence):
    words=break_words(sentence)
    print words
    print_frist_word(words)
    print_last_word(words)
def print_frist_and_last_sorted(sentence):
    words=sort_sentence(sentence)
    print words
    print_frist_word(words)
    print_last_word(words)

words=break_words("All good things come to those who wait")
print '打印出分隔的单词'
print words
print '返回排序后的结果'
print sort_words(words)
print '打印未排序的首单词'
print_frist_word(words)
print '打印未排序的尾单词'
print_last_word(words)

sentences=sort_sentence('All good things come to those who wait')
print '打印出分隔的单词'
print sentences
print '打印未排序的首尾单词'
print_frist_and_last('All good things come to those who wait')
print '打印排序的首尾单词'
print_frist_and_last_sorted('All good things come to those who wait')

知识点:复习函数

执行结果:

打印出分隔的单词
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
返回排序后的结果
['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
打印未排序的首单词
All
打印未排序的尾单词
wait
打印出分隔的单词
['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
打印未排序的首尾单词
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait']
All
wait
打印排序的首尾单词
['All', 'come', 'good', 'things', 'those', 'to', 'wait', 'who']
All
who

26.笨办法学 Python-第二十六

#!/usr/bin/python
#coding=utf-8
# 笨办法学 Python-第二十六题
#修改代码
def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words): #'错误1:函数定义后没有:'
    """Prints the first word after popping it off."""
    word = words.pop(0)     #错误10:pop拼写错误
    print word

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1) #错误2:少半个括号
    print word

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)


print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tabs.'

poem = """
\tThe lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
and requires an explantion
\n\t\twhere there is none.
"""


print "--------------"
print poem
print "--------------"

five = 10 - 2 + 3 - 5
print "This should be five: %s" % five

def secret_formula(started):
    jelly_beans = started * 500
    jars = jelly_beans /1000  #错误3:除法符号写出
    crates = jars / 100
    return jelly_beans, jars, crates


start_point = 10000
beans, jars, crates = secret_formula(start_point)#错误4,secret_formula函数的参数名错误,赋值操作符是=

print "With a starting point of: %d" % start_point
print "We'd have %d jeans, %d jars, and %d crates." % (beans, jars, crates)

start_point = start_point / 10

print "We can also do that this way:"
print "We'd have %d beans, %d jars, and %d crabapples." % secret_formula(start_point)#错误5:参数名写错


sentence = "All god\tthings come to those who weight."
'''
words = ex26.break_words(sentence)
sorted_words = ex25.sort_words(words)

print_first_word(words)
print_last_word(words)
.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
prin sorted_words

print_irst_and_last(sentence)

   print_first_a_last_sorted(senence)'''

words = break_words(sentence)
sorted_words = sort_words(words) #错误6:ex25应改改为ex26

print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)  #错误7:调用函数的时候不能够在前面加点
print_last_word(sorted_words)
sorted_words =sort_sentence(sentence)
print sorted_words   #错误8:print拼写错误

print_first_and_last(sentence)  #错误9,函数调用名称写错

print_first_and_last_sorted(sentence)

知识点:细节决定一切!

至此,习题已经做了一半了.

 

© 著作权归作者所有

上一篇: 笨方法学python IV
下一篇: 笨方法学python II
渺渺星辰
粉丝 3
博文 33
码字总数 34632
作品 0
海淀
私信 提问
20 本优秀的 Python 电子书

想要学习Python编程语言的读者有大量相关书籍可供选择,有印刷版也有电子版,而Python是一门开源的编译语言,开发者也提供了不少免费可自由下载的Python电子书。本文挑选其中最优秀的20本Pyt...

oschina
2012/12/30
11.4K
19
无法理解有关Python字典/hash的一段代码

我正在用Learn Python The Hard Way(笨方法学Python)入门Python,这也是我学习编程的第一个语言。今天遇到一个问题,查了很久的谷歌还是无法解决。 链接在这里: http://learnpythonthehar...

好好先生_1028
2015/06/29
443
2
python-35:urllib 和 urllib2 模块

首先,urllib 和 urllib2 是python 自带的模块,所以我们可以通过官网文档来查看它们的详细信息,这里依然给出网址,感兴趣的同学可以看一下 urllib模块:http://python.usyiyi.cn/python278...

达岭凹老大
2015/12/01
333
0
我们可以在同一个虚拟机中运行 Python 2 和 3 代码而不需要更改代码吗?

从理论上来说,可以。Zed Shaw 说过一句著名的话,如果不行,那么 Python 3 一定不是图灵完备的。但在实践中,这是不现实的,我将通过给你们举几个例子来说明原因。 对于字典(dict)来说,这...

作者: Łukasz Langa
2018/05/08
0
0
[深度基础]·小白如何快速入门深度学习

[深度基础]·小白如何快速入门深度学习 个人主页--> https://xiaosongshine.github.io/ 随着近年深度学习的兴起,很多研究者都投入这个领域当中,由于各个大学都将自己的课程放到了网上,出现...

小宋是呢
03/26
0
0

没有更多内容

加载失败,请刷新页面

加载更多

反编译9.png图片还原

本文链接:https://blog.csdn.net/a1140778530/article/details/10528507 经常反编译apk文件找资源,9.png的文件处理起来很麻烦。 最近使用Ant自动编译打包app时,从别处搜罗来的9.png文件导...

shzwork
14分钟前
2
0
Shell脚本应用 – for、while循环语句

一、for循环语句 在实际工作中,经常会遇到某项任务需要多次执行的情况,而每次执行时仅仅是处理的对象不一样,其他命令相同。例如:根据通讯录中的姓名列表创建系统账号等情况。 当面对各种...

linux-tao
14分钟前
3
0
RPA风潮下企业财务工作模式的变革

RPA(机器人流程自动化)在财务领域的应用,正给企业财务带来前所未有的改变。 前RPA时代,财务领域面临的痛点 在RPA机器人应用之前,企业财务工作进程的推进,主要通过财务人员人工操作或信...

UiBot
19分钟前
3
0
Hive之命令行修改表注释

最近遇到一个需求,在不重建表的情况下,修改表的注释,hive有没有类似关系型数据库的SQL命令来修改呢,找了下,亲测有效,如下List-1 List-1 hive>use your_schemahvie>ALTER TABLE tabl...

克虏伯
20分钟前
3
0
是什么,它的作用是什么

在HTML文档的首部往往会有这么一句话<!DOCTYPE html>,许多时候我们忽视了它的存在,它实际上是一个声明,告诉浏览器用哪种HTML版本的规范来解读HTML文档。 尽管我们不给出这句声明浏览器照样...

前端老手
25分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部