一. 作业内容
笨办法学Python习题18-26
二. 作业代码
习题18
# 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 nothing.')
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 nothing.
附加练习
函数定义以def开始,和变量名一样,只要以字母,数字以及下划线组成,而且不是数字开始,就可以了。函数名紧跟着括号(,括号里可以包括参数,也可以不包括参数。多个参数以逗号隔开。参数名称不能重复。紧跟着的参数的是括号和冒号 ():)。紧跟着函数定义的代码要使用4个空格的缩进。函数结束的位置取消了缩进。
运行一个函数时,要检查以下要点:
- 调用函数时是否使用了函数名。
- 函数名是否紧跟着(。
- 括号后有无参数, 多个参数是否以逗号隔开。
- 函数是否以)结尾。
心得体会:
对于函数的名称,要避开python内置的关键词。获得python关键词的方法是
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
习题19
def cheese_and_crackers(cheese_count, boxes_of_crackers): #定义一个函数,内含2个参数
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) # 给函数传递数学表达式和变量
应该看到的结果
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.
附加练习
3 编写一个函数
def python_homework(complete_date, complete_quality):
print('I do the homework on %s and complete it %s at last' %(complete_date, complete_quality))
python_homework('21-JUL-2017', 'very good')
date_one = '22-JUL-2017'
quality_one = 'bad'
python_homework(date_one, quality_one)
print('please enter a date for the python homework you do')
date_one = input('> ')
print('please enter the quality for the python homework you do')
quality_one = input('> ')
python_homework(date_one, quality_one)
I do the homework on 21-JUL-2017 and complete it very good at last
I do the homework on 22-JUL-2017 and complete it bad at last
please enter a date for the python homework you do
> 20-JUN-2017
please enter the quality for the python homework you do
> VERY GOOD
I do the homework on 20-JUN-2017 and complete it VERY GOOD at last
心得体会: int() 把input()的值转化为整数。不可以把全局变量的名称和函数变量的名称取成一样的。
习题20 函数和文件
from sys import argv #从sys模块导入参数argv
script, input_file = argv #把参数argv解包成两个参数:script和input_file
def print_all(f): #定义一个函数 print_all(), 传递的参数是f
print(f.read()) #打印f的内容
def rewind(f): #定义一个函数rewind, 传递的参数是f
f.seek(0) # 从文件f的开始位置读起
def print_a_line(line_count, f): #定义一个函数print_a_line, 传递的参数是line_count 和f
print (line_count, f.readline()) # 打印line_count, 读取文件f当前行
current_file = open(input_file) # 打开所输入的文件, 把这个方法赋值给变量current_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 #把1赋值给current_line
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:
Lear
Python
the
hard
way
Now let's rewind, kind of like a tape
Let's print three lines:
1 Lear
2 Python
3 the
附加练习:
- file中的seek函数是读取位置, seek(0)代表从起始位置读起,seek(1) 从当前位置读起,seek(2) 从末尾位置读起。 tell(): 文件的当前位置,即tell是获得文件指针位置。readline(n):读入若干行,n表示读入的最长字节数。其中读取的开始位置为tell()+1。当n为空时,默认只读当前行的内容。readlines读入所有行内容,read读入所有行内容。
- 操作符 +=, 例如x+=1表示 x=x+1
习题21 函数可以返回某些东西
def add(a, b):
print('Adding %d + %d' %(a, b))
return a + b
def substract(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 divided(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 = substract(78, 4)
weight = multiply(90, 2)
iq = divided(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.
print('Here is a puzzle.')
what = add(age, substract(height, multiply(weight, divided(iq, 2))))
print('That becomes:', what, 'Can you do it by hand?')
应该看到的结果
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.0 Can you do it by hand?
附加练习
def add(a, b):
print('Adding %d + %d' % (a, b))
return a + b
age = add(30, 5)
print('Age: %d' %(age))
结果
Adding 30 + 5
Age: 35
习题24 更多练习
print('Let\'s practice everything.')
print('You\'d need to known\'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 requireds 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): # 定义一个函数,其参数为started
jelly_beans = started * 500 # 把参数started × 500赋值给变量jelly_beans
jars = jelly_beans / 1000 # 把jelly_beans/1000 赋值给jars
crates =jars / 100 #把 jars/100 赋值给crates
return jelly_beans, jars, crates #返回jelly_beans, jars, crates
start_point = 10000 #把10000赋值给变量start_point
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))
应该看到的结果
Let's practice everything.
You'd need to known'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 requireds 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.
心得体会:
python3中 print‘’‘ ’‘’相当于python2 中的 “”“ ”“”,可以引用一段话
return表示返回函数的值
习题25 更多更多的实践
def break_words(stuff):
'''This function will break up words for us.'''
words = stuff. split(' ')
return words
#sentence = "I am writing python."
#b = break_words(sentence)
#print(b)
def sort_words(words):
return sorted(words)
#sentence1 = "i am writing python"
#a = sort_words(sentence)
#print(a)
def print_first_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_first_and_last(sentence):
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
image.png
附加练习
2,执行help(ex25)和help(ex25.break_words)
心得体会:
习题25的函数需要在命令行的python的交互模式下进行, 即先cd ex25.py所在的路径, 进入python,再import ex25,即可让程序运行下去。
"""This function will break up words for us.""" 这是函数的帮助文档。
习题26 考试
修改后的代码如下
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_sentence(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
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 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))
sentence = "All god\tthings come to those who weight."
from ex25 import *
words = break_words(sentence)
sorted_words = sort_words(words)
print_first_word(words)
print_last_word(words)
print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = sort_sentence(sentence)
print (sorted_words)
print_first_and_last(sentence)
print_first_and_last_sorted(sentence)
运行结果如下:
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 explantion
where there is none.
--------------
This should be five: 6
With a starting point of: 10000
We'd have 5000000 jeans, 5000 jars, and 50 crates.
We can also do that this way:
We'd have 500000 beans, 500 jars, and 5 crabapples.
All
weight.
All
who
['All', 'come', 'god\tthings', 'those', 'to', 'weight.', 'who']
All
weight.
All
who
心得体会:
移除import ex25.py, 那部分关于ex25的代码将不会运行。
网友评论