- 习题18 命名、变量、代码、函数
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args # 将参数解包,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): # 传递两个参数,def print_two(*args): + arg1, arg2 = args 作用一样,合并了指定参数和参数解包的过程
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.紧跟着函数定义的代码使用了4个空格的缩进,表示这段代码包含在函数定义代码块中;
8.函数结束的位置/下一个代码段的开始,取消缩进。
函数调用注意事项:
1.使用函数名称调用函数;
2.函数名称后紧跟着括号;
3.根据函数定义,传递与定义中个数相符、顺序相符的实参,多个参数之间以逗号隔开;
4.函数调用以)结果表示传递参数结束;
5.被调用函数的名称需与被定义的函数名称完全一致。
- 习题19 函数和变量
# 定义一个函数cheese_and_crackers,包含两个参数,cheese_count和boxes_of_crackers。这个函数执行4个打印的任务。
def cheese_and_crackers(cheese_count, boxes_of_carckers):
print("You have %d cheeses!" % cheese_count)
print("You have %d boxes of crackers!" % boxes_of_carckers)
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) # 调用函数cheese_and_crackers函数,传递两个参数,cheese_count = 20, boxes_of_crackers = 30
# 另外一种方式给函数传递参数
print("Or, we cam 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_crackers + 100, amount_of_crackers + 1000) # 在函数中做运算
加分习题:
19.2 自己编至少一个函数出来,
# 指定一个数,输出从1到这个数(包含这个数)之间的所有数字
def f(n):
current_number = 1
while current_number <= n:
print(current_number)
current_number += 1
f(6) # 输出结果为 1 2 3 4 5 6
- 习题20 函数和文件
from sys import argv # 从sys模块调用argv函数
script, input_file = argv # 解包argv,需要传递脚本名称script和input_file的名称
# 读取f文件内容并打印
def print_all(f):
print(f.read())
# 移动文件读取指针到文件开头
def rewind(f):
f.seek(0) # seek() 方法用于移动文件读取指针到指定位置。
# 每次读一行,并计数
def print_a_line(line_count, f):
print(line_count, f.readline()) # readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字
current_file = open(input_file) # 打开文件,并将对象存储于current_file变量
print("Frist 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 # 等同于current_line += 1
print_a_line(current_line, current_file)
# 读取文件第三行,并计数,输出行号与行内容
current_line = current_line + 1
print_a_line(current_line, current_file)
学习笔记:关于readline()函数的行读取方式
备注:readline()每运行一次,读取一行,print_a_line运行三次就会依次打印1,2,3行,而不是打印第一行三次。
current_line = 1
print_a_line(current_line, current_file) # 打印第一行
print_a_line(current_line, current_file) # 打印第二行
print_a_line(current_line, current_file) # 打印第三行
- 习题21 函数可以返回东西
def add(a, b): # 定义一个函数,这个函数有两个任务,打印一段文字,并将参数的和返回给函数
print("ADDING %d + %d" % (a, b))
return a + b
def substract(a, b):
print("SUBSTRACTING %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) # print(age) 输出值35.但是age = add(30,5)的结果为print("ADDING %d + %d" % (a, b))。
height = substract(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.
print("Here is a puzzle.")
what = add(age, substract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
- 习题24 更多练习
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 lovely
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
""" # \t换行符,\n缩进,''''''输出多行内容
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))
- 习题25 更多更多练习
import ex25 as p # 将文件夹中的ex25.py导入到此程序中,且命名为p
sentence = "All good things come to those who wait."
words = p.break_words(sentence) # 句点法调用ex25中的函数
print(words)
sorted_words = p.sort_words(words)
print(sorted_words)
p.print_first_word(words)
p.print_last_word(words)
# print(wrods) # name 'wrods' is not defined
print(words)
p.print_first_word(sorted_words)
p.print_last_word(sorted_words)
print(sorted_words)
sorted_words = p.sort_sentence(sentence)
print(sorted_words)
p.print_first_and_last(sentence)
p.print_first_and_last_sorted(sentence)
学习笔记:关注模组和函数的导入
《笨办法学Pyhton》中是在先运行ex25.py,然后再python编译器里进行的交互练习。
我的代码里是在ex25.py的同一个目录下新建了一个py文件,然后import ex25 as p将ex25导入到程序中,再使用句点法调用ex25.py中定义的函数。
- 习题26 考试(改错)
import ex25
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)
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 good things come to those who wait."
words = ex25.break_words(sentence)
sorted_words = ex25.sort_words(words)
print_first_word(words)
print_last_word(words)
ex25.print_first_word(sorted_words)
print_last_word(sorted_words)
sorted_words = ex25.sort_sentence(sentence)
print(sorted_words)
print_first_and_last(sentence)
print_first_and_last(sentence)
学习笔记:
**
代码常见语法错误
①函数定义def f()后缺少:
②print要讲打印的内容放在()内;
③除号是/而不是\;
④缩进错误;
⑤与-的输入错误,另外函数名及参数名都只能是字母与数字以及的组合,并且不能以数字开头;
⑥使用了未定义的参数名、变量名;
⑦调用模组或模组中的函数需在代码前几行先导入;
⑧函数名、变量名输入错误。
**
心得体会:
新手学习python最容易犯的代码错误有两种,分别是语法错误、逻辑错误。
语法错误是指代码违背了代码语言的语法,例如括号不匹配、变量名称书写错误、使用了未定义的变量名等等,导致编译器进行语法检查时不通过。
逻辑错误是程序能运行,但是达不到预期结果。
语法错误很容易犯,很多细微的差别都可能使编译器报错。除了写代码时要细心之外,我们还要学会通过编译器的错误代码,发现错误并快速定位、改写语法错误的代码。
Pycharm、Sublime Txt等工具都自带语法高亮、错误提示,善用这些工具能够极大提高我们的效率,减少语法错误。