author:headsen chen

date:2018-06-01 15:39:26

习题17,文件的更多操作

[root@localhost py]# echo 1234567890 >cc.txt

[root@localhost py]# cat file3.py

#!/usr/bin/env pythonfromsys import argvfromos.path import exists

script,from_file,to_file=argv

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

# we coulddo these two on one line too,how?input=open(from_file)

indata=input.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."raw_input()

output= open(to_file,'w')

output.write(indata)

print"Alright,all done."output.close()

input.close()

[root@localhost py]#python file3.py cc.txt dd.txt

Copying fromcc.txt to dd.txt

The input fileis 11bytes long

Does the output file exist? True

Ready,hit RETURN tocontinue, CTRL-C to abort.

Alright,all done.

检验新生成的dd.txt文件:

[root@localhost py]# cat dd.txt

1234567890

这里不过dd.txt是否存在,若存在:清空然后复制cc.txt的内容过来,若不存在dd.txt文件就创建dd.txt文件并复制内容过来

补充:exists这个命令将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False。

习题18:函数 ---> 理解成“迷你脚本”

函数可以做三样事情:

1.它们给代码片段命名,就跟“变量”给字符串和数字命名一样。

2.它们可以接受参数,就跟你的脚本接受 argv 一样。

3.通过使用 #1 和 #2,它们可以让你创建“微型脚本”或者“小命令”。

[root@localhost py]#cat func1.py#!/usr/bin/env python

#this is like you scripts with argv

def print_two(*args):

arg1,arg2=argsprint "arg1:%r,arg2:%r" %(arg1,arg2)#ok,that *args is actually pointless,we can just do this

defprint_two_again(arg1,arg2):print "arg1:%r,arg2:%r" %(arg1,arg2)#this just takes one argument

defprint_one(arg1):print "arg1:%r"%arg1#this one takes no arguments

defprint_none():print "I got nothing."print_two('zen','hello')

print_two_again('ZEN','HELLO')

print_one('First!')

print_none()

[root@localhost py]#python func1.py

arg1:'zen',arg2:'hello'arg1:'ZEN',arg2:'HELLO'arg1:'First!'I got nothing.

习题 19: 函数和变量

[root@localhost py]#cat func2.py#!/usr/bin/env python

defcheese_and_crackers(cheese_count, boxes_of_crackers):print "You have %d cheeses!" %cheese_countprint "You have %d boxes of crackers!" %boxes_of_crackersprint "Man that's enough for a party!"

print "Get a blanket.\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= 10amount_of_crackers= 50cheese_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)

[root@localhost py]#python func2.py

We can just give the function numbers directly:

You have20cheeses!

You have30boxes of crackers!

Man that's enough for a party!

Get a blanket.

OR, we can use variablesfromour script:

You have10cheeses!

You have50boxes of crackers!

Man that's enough for a party!

Get a blanket.

We can even do math inside too:

You have30cheeses!

You have11boxes of crackers!

Man that's enough for a party!

Get a blanket.

And we can combine the two, variablesandmath:

You have110cheeses!

You have1050boxes of crackers!

Man that's enough for a party!

Get a blanket.

习题 20: 函数和文件

[root@localhost py]#cat aa.txt

aaaaaa

bbbbbb

cccccc

[root@localhost py]#cat func-file.py

#!/usr/bin/env python

from sys importargv

script, input_file=argvdefprint_all(f):printf.read()defrewind(f):

f.seek(0)defprint_a_line(line_count, f):printline_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= 1print_a_line(current_line, current_file)

current_line= current_line + 1print_a_line(current_line, current_file)

current_line= current_line + 1print_a_line(current_line, current_file)

[root@localhost py]#python func-file.py aa.txt

First let's print the whole file:

aaaaaa

bbbbbb

cccccc

Now let's rewind, kind of like a tape.

Let's print three lines:

1aaaaaa2bbbbbb3 cccccc

习题 21: 函数可以返回东西

[root@localhost py]#cat func-return.py#!/usr/bin/env python#-*- coding:utf-8 -*-

defadd(a, b):print "ADDING %d + %d" %(a, b)return a +bdefsubtract(a, b):print "SUBTRACTING %d - %d" %(a, b)return a -bdefmultiply(a, b):print "MULTIPLYING %d * %d" %(a, b)return a *bdefdivide(a, b):print "DIVIDING %d / %d" %(a, b)return a /bprint "Let's do some math with just functions!"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)#A puzzle for the extra credit, type it in anyway.# pullzle:智力题

print "Here is a puzzle."what= add(age, subtract(height, multiply(weight, divide(iq,2))))print "That becomes:", what, "Can you do it by hand?"

[root@localhost py]#python func-return.py

Let's do some math with just functions!

ADDING 30 + 5SUBTRACTING78 - 4MULTIPLYING90 * 2DIVIDING100 / 2Age:35, Height: 74, Weight: 180, IQ: 50Hereisa puzzle.

DIVIDING50 / 2MULTIPLYING180 * 25SUBTRACTING74 - 4500ADDING35 + -4426That becomes:-4391 Can you do it by hand?

习题 24: 练习

[root@localhost py]#cat practise.py#!/usr/bin/env python

print "Let's practice everything."

print 'You\'d need to know \'bout escapes with \\ that do \nnewlines 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 explanation

\n\t\twhere there is none."""

print "--------------"

printpoemprint "--------------"five= 10 - 2 + 3 - 6

print "This should be five: %s" %fivedefsecret_formula(started):

jelly_beans= started * 500jars= jelly_beans / 1000crates= jars / 100

returnjelly_beans, jars, crates

start_point= 10000beans, jars, crates=secret_formula(start_point)print "With a starting point of: %d" %start_pointprint "We'd have %d beans, %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 crates." %secret_formula(start_point)

[root@localhost py]#python practise.py

Let's practice everything.

You'd need to know'bout escapes with \ that do

newlinesandtabs.--------------The lovely world

with logic so firmly planted

cannot discern

the needs of love

nor comprehend passionfromintuitionandrequires an explanation

where thereisnone.--------------This should be five:5With a starting point of:10000We'd have 5000000 beans, 5000 jars, and 50 crates.

We can also do that this way:

We'd have 500000 beans, 500 jars, and 5 crates.

习题 25: 更多的练习

[root@localhost py]#cat practise2.py#!/usr/bin/env python

defbreak_words(stuff):"""This function will break up words for us."""words= stuff.split('')returnwordsdefsort_words(words):"""Sorts the words."""

returnsorted(words)defprint_first_word(words):"""Prints the first word after popping it off."""word=words.pop(0)printworddefprint_last_word(words):"""Prints the last word after popping it off."""word= words.pop(-1)printworddefsort_sentence(sentence):"""Takes in a full sentence and returns the sorted words."""words=break_words(sentence)returnsort_words(words)defprint_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)defprint_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)

习题26:逻辑术语

在 python 中我们会用到下面的术语(字符或者词汇)来定义事物的真(True)或者假(False)。计算机的逻辑就是在程序的某个位置检查这些字符或者变量组合

在一起表达的结果是真是假。

 and 与

 or 或

 not 非

 != (not equal) 不等于

 == (equal) 等于

 >= (greater-than-equal) 大于等于

 <= (less-than-equal) 小于等于

 True 真

 False 假

真值表

我们将使用这些字符来创建你需要记住的真值表。

not False True

not True False

True or FalseTrue

True or True True

False or True True

False or False False

True and FalseFalse

True and True True

False and True False

False and False False

not (True or False) False

not (True or True) False

not (False or True) False

not (False or False) True

not (True and False) True

not (True and True) False

not (False and True) True

not (False and False) True

1 != 0 True

1 != 1 False

0 != 1 True

0 != 0 False

1 == 0 False

1 == 1 True

0 == 1 False

0 == 0 True

习题27:bool 值运算

[root@localhost py]# cat bool.py

#!/usr/bin/env python

print True and True

print False and True

print 1 == 1 and 2 == 1

print "test" == "test"

print 1 == 1 or 2 != 1

print True and 1 == 1

print False and 0 != 0

print True or 1 == 1

print "test" == "testing"

print 1 != 0 and 2 == 1

print "test" != "testing"

print "test" == 1

print not (True and False)

print not (1 == 1 and 0 != 1)

print not (10 == 1 or 1000 == 1000)

print not (1 != 10 or 3 == 4)

print not ("testing" == "testing" and "Zed" == "Cool Guy")

print 1 == 1 and not ("testing" == 1 or 1 == 0)

print "chunky" == "bacon" and not (3 == 4 or 3 == 3)

print 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")

[root@localhost py]# python bool.py

True

False

False

True

True

True

False

True

False

False

True

False

True

False

False

False

True

True

False

False

习题28:bool运算

3 != 4 and not ("testing" != "test" or "Python" == "Python")

接下来你将看到这个复杂表达式是如何逐级解为一个单独结果的:1. 解出每一个等值判断:

a.3 != 4 为 True : True and not ("testing" != "test" or "P

ython"=="Python")

b. "testing" != "test" 为 True : True and not (True or "Pyt

hon"=="Python")

c. "Python" == "Python" : True and not (True orTrue)2. 找到括号中的每一个 and/or:

a. (Trueor True) 为 True: True and not(True)3. 找到每一个 not并将其逆转:

a.not (True) 为 False: True andFalse4. 找到剩下的 and/or,解出它们的值:

a. TrueandFalse 为 False

这样我们就解出了它最终的值为 False.

View Code

习题 29: 如果(if)

[root@localhost py]#cat if.py#!/usr/bin/env python

people = 20cats= 30dogs= 15

if people

if people >cats:print "Not many cats! The world is saved!"

if people

if people >dogs:print "The world is dry!"dogs+= 5

if people >=dogs:print "People are greater than or equal to dogs."

if people <=dogs:print "People are less than or equal to dogs."

if people ==dogs:print "People are dogs."

View Code

[root@localhost py]#python if.py

Too many cats! The world isdoomed!

The worldisdry!

People are greater thanorequal to dogs.

People are less thanorequal to dogs.

People are dogs.

View Code

习题30:if -elase 结合使用

[root@localhost py]#cat if.py#!/usr/bin/env python

people = 20cats= 30dogs= 15

if people

if people >cats:print "Not many cats! The world is saved!"

if people

if people >dogs:print "The world is dry!"dogs+= 5

if people >=dogs:print "People are greater than or equal to dogs."

if people <=dogs:print "People are less than or equal to dogs."

if people ==dogs:print "People are dogs."

View Code

[root@localhost py]# python if-else.py

We should take the cars.

Maybe we could take the buses.

Alright, let's just take the buses.

python集合例题_python练习题集合-2相关推荐

  1. python递归函数例题_python练习题----函数、内置函数、递归等

    1. 列举布尔值为False的值 { }.' '.0.().[ ].False.None2.根据范围获取其中3和7整除的所有数的和,并返回调用者:符合条件的数字个数以及符合条件数字的总和 #自答 fr ...

  2. python递归函数例题_Python练习题 022:用递归函数反转字符串

    原博文 2016-10-17 16:24 − [Python练习题 022] 利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来. ----------------------------- ...

  3. python 字符串交集_Python序列--集合(set)

    集合 集合用于保存不重复元素. - 集合和列表非常相似 - 不同点: 1.集合中只能存储不可变对象 2.集合中存储的对象是无序(不是按照元素的插入顺序保存) 3.集合中不能出现重复的元素 集合的所有元 ...

  4. [转载] python set大小_python set集合

    参考链接: Python集合set Python set集合 最后更新于:2020-03-21 12:06:03 在python变量中除了以前文章所提到的整形int / 浮点数float / 布尔值b ...

  5. [转载] python创建集合set()_python 之集合{}(Set)

    参考链接: Python 集合set pop() 集合# 集合set 是装有独特值的无序"袋子".一个简单的集合可以包含任何数据类型的值.如果有两个集合,则可以执行像联合.交集以及 ...

  6. python set大小_python set集合

    集合set 可变的 无序的 不重复的元素集合 set定义 初始化 set() 生成一个空集合 set(iterable) 可通过可迭代对象生产一个新的集合 s1 =set() s2= set(rang ...

  7. python集合输出_Python之集合

    集合:无序的,不可随机访问的,不可重复的元素集合 # 可以使用大括号 { } 或者 set() 函数创建集合, # 注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个 ...

  8. python集合例题_python基础练习题、集合的讲解、一些公关方法

    1.求100(含100)以内所有偶数的和 range(start,end,step)这个序列生成器,和那个切片的语法一样,含头不含尾,step是步长,这里就不需要在对j进行判断了,对于这些简单求奇数和 ...

  9. python集合例题_python 学到集合为止的17道练习题

    print('-------练习1.2-----------') 1.简述变量命名规范. 本题原文:https://blog..net/yirentianran/article/details/795 ...

最新文章

  1. [CF888G]Xor-MST
  2. 项目管理过程中,如何编制初步工作说明书
  3. mysql 主从 网络异常_mysql主从常见异常问题解决
  4. RGB HSV HLS三种色彩模式转换(C语言实现)
  5. C#泛型对类型参数的推断
  6. 阿里P8架构师谈:分布式、集群、负载均衡、分布式数据一致性的区别与关联
  7. oracle 如何迁移到 mysql_怎么将数据库从Oracle迁移到SQL Server,或从Oracle迁移到MySQL...
  8. Java面试:Java面试总结PDF版
  9. Htmlimg标签特写 2017-03-10 AM
  10. 解析vue-ssr构建流程
  11. Mac系统下设置Maven环境
  12. IDEA的Database表的基本操作
  13. wps表格在拟合曲线找点_用excel寻找拟合曲线上的某一点的使用方法
  14. 计算机职业素养论文1500字,职业素养论文1500字 [职业素养教育论文]
  15. LeetCode #780 - Reaching Points
  16. 后N天C语言,c语言计算一个日期的下一天后N天后的日期
  17. 得力标签打印机,驱动程序安装不上,手动安装好打印没反应
  18. awk sed grep find sort常用配搭用法
  19. 天涯孤岸软件商城-.net电子商务网站系统案例
  20. “da shen” in my heart

热门文章

  1. android 获得屏幕的大小
  2. Windows程序闪退Windows日志捕获Kernelbase模块错误
  3. 对RESTful Web API的理解与设计思路
  4. Asp.Net生命周期系列三
  5. sql server 2008学习2 文件和文件组
  6. 【SpringBoot MQ 系列】RabbitListener 消费基本使用姿势介绍
  7. [MySQL]MySQL分区与传统的分库分表(精华)
  8. 统计Apache或nginx日志里访问次数最多的前十个IP
  9. Linux的换网变化IP进行固定IP
  10. python决策树可视化_「决策树」| Part3—Python实现之可视化