author:headsen chen

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

习题17,文件的更多操作

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

[root@localhost py]# cat file3.py
#!/usr/bin/env 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 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 from cc.txt to dd.txt
The input file is 11 bytes long
Does the output file exist? True
Ready,hit RETURN to continue, 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 = 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 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
def cheese_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'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 = 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)
[root@localhost py]# python func2.py
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers!
Man that's enough for a party!
Get a blanket. OR, we can use variables from our script:
You have 10 cheeses!
You have 50 boxes of crackers!
Man that's 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's enough for a party!
Get a blanket. And we can combine the two, variables and math:
You have 110 cheeses!
You have 1050 boxes 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 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)
[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:
1 aaaaaa 2 bbbbbb 3 cccccc

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

[root@localhost py]# cat func-return.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b print "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 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That 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 "--------------"
print poem
print "--------------"
five = 10 - 2 + 3 - 6
print "This should be five: %s" % five def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
beans, jars, crates = secret_formula(start_point)
print "With a starting point of: %d" % start_point
print "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
newlines and tabs.
-------------- The lovely world
with logic so firmly planted
cannot discern
the needs of love
nor comprehend passion from intuition
and requires an explanation where there is none. --------------
This should be five: 5
With a starting point of: 10000
We'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
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):
"""Prints the first word after popping it off."""
word = words.pop(0)
print word
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
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)

习题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 False True
True or True True
False or True True
False or False False

True and False False
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 or True) 2. 找到括号中的每一个 and/or :
a. (True or True) 为 True: True and not (True) 3. 找到每一个 not 并将其逆转:
a. not (True) 为 False: True and False 4. 找到剩下的 and/or,解出它们的值:
a. True and False 为 False 这样我们就解出了它最终的值为 False.

习题 29: 如果(if)

[root@localhost py]# cat if.py
#!/usr/bin/env python
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
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."
[root@localhost py]# python if.py
Too many cats! The world is doomed!
The world is dry!
People are greater than or equal to dogs.
People are less than or equal to dogs.
People are dogs.

习题30:if -elase 结合使用

[root@localhost py]# cat if.py
#!/usr/bin/env python
people = 20
cats = 30
dogs = 15
if people < cats:
print "Too many cats! The world is doomed!"
if people > cats:
print "Not many cats! The world is saved!"
if people < dogs:
print "The world is drooled on!"
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."
[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练习题集合-2的更多相关文章

  1. python练习题集合-1

    author:headsen chen  date : 2018-05-31  17:59:04 notice:本文素材来自于:<< 笨方法学python >> 这本书,由本人 ...

  2. Python练习题 001:4个数字求不重复的3位数

    听说做练习是掌握一门编程语言的最佳途径,那就争取先做满100道题吧. ----------------------------------------------------------------- ...

  3. Python练习题 028:求3*3矩阵对角线数字之和

    [Python练习题 028] 求一个3*3矩阵对角线元素之和 ----------------------------------------------------- 这题解倒是解出来了,但总觉得 ...

  4. Python练习题 027:对10个数字进行排序

    [Python练习题 027] 对10个数字进行排序 --------------------------------------------- 这题没什么好说的,用 str.split(' ') 获 ...

  5. Python练习题 026:求100以内的素数

    [Python练习题 026] 求100以内的素数. ------------------------------------------------- 奇怪,求解素数的题,之前不是做过了吗?难道是想 ...

  6. Python练习题 025:判断回文数

    [Python练习题 025] 一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同. ---------------------------------------- ...

  7. Python练习题 024:求位数及逆序打印

    [Python练习题 024] 给一个不多于5位的正整数,要求:一.求它是几位数,二.逆序打印出各位数字. ---------------------------------------------- ...

  8. Python练习题 004:判断某日期是该年的第几天

    [Python练习题 004]输入某年某月某日,判断这一天是这一年的第几天? ---------------------------------------------- 这题竟然写了 28 行代码! ...

  9. Python 3 集合基础和概念!

    Python 3 集合基础和概念! Python 3中,集合是无序的,所以不能进行切片和索引操作. 创建集合有两个方法:set()方法创建的集合是可变的,可被迭代的:frozenset()方法创建的集 ...

随机推荐

  1. CentOS 之 Supervisor

    CentOS 之 Supervisor supervisor是一个Linux上用来管理程序后台运行的工具,支持程序的自启动,挂掉重启,日志等功能.可配置程序随系统启动,并支持挂掉重启,增强程序稳定性. ...

  2. hibernate 中集合的保存

    一.开发流程 1)引入jar包,注意引入数据库驱动包 2)创建数据库表 //创建用户表 CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, un ...

  3. atitit.产品console 日志的aticonsole 方案处理总结

    atitit.产品console 日志的aticonsole 方案处理总结 1. 主要原理流程 1 2. 调用代码 1 3. 内部主要实现 1 3.1. 放入消息 1 3.2. 读取消息 2 默认可以 ...

  4. [svc]sudo su权限案例

    一 控制sudo 允许执行所有命令,排除某几个命令(带参数) lanny ALL=(ALL) NOPASSWD:ALL, !/bin/su - root, !/usr/sbin/visudo 如果需要 ...

  5. 记一次处理IE引起的上网异常处理

    win7 64bit系统,IE(11)出问题.在更新记录里找不到IE11的更新项,也就无法通过正常卸载了.而网上的各种折腾卸载方式均宣告无效.后来无意间找到了一款国外大神开发的软件:RemoveIE, ...

  6. jdom 读取

    读取XML文档 读取文档,首先需要一个xml的解析器,它可以自动的解析出各个元素,并且把子元素作为自己的孩子节点,方便操作. 主要使用的函数: SAXBuilder.build("xxx.x ...

  7. STM32 中断应用概览

    本章参考资料< STM32F4xx 中文参考手册>第十章-中断和事件.<ARM Cortex™-M4F 技术参考手册> -4.3 章节: NVIC 和 4.4 章节: SCB— ...

  8. C语言 · 三角形面积

     算法提高 三角形面积   时间限制:1.0s   内存限制:256.0MB      问题描述 由三角形的三边长,求其面积. 提示:由三角形的三边a,b,c求面积可以用如下的公式: s=(a+b+c ...

  9. VMware12激活码,win10激活码

    VMware Workstation 12序列号: 5A02H-AU243-TZJ49-GTC7K-3C61N win10激活码:这里在网上搜集到很多激活码,可能有的不能用.   WRUF7-AFI0 ...

  10. Okra框架(三) 搭建HTTP服务器

    Okra通过封装成熟高效的框架以简化应用程序服务器构建的过程.上一篇介绍了使用Okra快速搭建Socket服务器. 本篇承接上一篇,介绍快速搭建简单高性能的Http服务器. 这里需要说明一下Okra框 ...