习题21:函数可以返回某些东西
代码
def add(a,b):
print(f"Adding {a} + {b}")
return a+b
def subtract(a,b):
print(f"Substracting {a} - {b}")
return a-b
def multiply(a,b):
print(f"multiplying {a} * {b}")
return a*b
def divide(a,b):
print(f"dividing {a}/{b}")
return a/b
print("Let's do some match with just functions!")
age = add(30,5)
height = subtract(78,4)
weight = multiply(90,2)
iq = divide(100,2)
print(f"Age: {age},Height:{height},IQ :{iq}")
#A puzzle for the extra credit,type it in anyway.
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?")
#正常的公式来重新创建同样一组运算。
a=divide(iq,2)
b=multiply(weight,a)
c=subtract(height,b)
d=add(age,c)
print("again:",d )
知识点
- return语句用来退出函数并将程序返回到函数被调用的位置继续执行。return语句可以同时将0个、1个或多个函数运算后的结果返回给函数被调用处的变量。当然,函数也可以没有return,此时函数并不返回值。在函数体结束位置将控制权返回给调用者。函数也可以用return 返回多个值,多个值以元组类型保存。
- 浮点数float ,整数int。int(input()) float(input())
- 函数是由内向外打印的,没毛病。
破坏程序
- 破坏程序一:无return,则返回None
def multiply(a,b):
print(f"multiplying {a} * {b}")
# return a*b
PS C:\Users\WU\pyfile> python ex21.py
Let's do some match with just functions!
Adding 30 + 5
Substracting 78 - 4
multiplying 90 * 2
dividing 100/2
Age: 35,Height:74,IQ :50.0
Here is a puzzle.
dividing 50.0/2
multiplying None * 25.0
Substracting 74 - None
Traceback (most recent call last):
File "C:\Users\WU\pyfile\ex21.py", line 23, in <module>
what = add(age,subtract(height,multiply(weight,divide(iq,2))))
File "C:\Users\WU\pyfile\ex21.py", line 6, in subtract
return a-b
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
习题22:到现在为止你学到了什么
作者提示:
1.没有失败,只有尝试。
2.回顾符号列表 查询符号的作用
3. 这个慢慢来,这会让我们明确目标,让我知道自己所有努力的目的。
习题23:字符串、字节串和字符编码
- To do this exercise you’ll need to download a text file that I’ve written named languages.txt
( https://learnpythonthehardway.org/python3/languages.txt ) This file was created with a list of human languages to demonstrate a few interesting concepts.
习题24:更多的练习
代码
print("Let's practice everying")
print('You\'d need to know \'bout escape with \\ that do:') #输出字符串,\'即',\\即\
print('\n newlines and \t tabs.') #输出字符串,\n =newline换行,\t = Tabs,四个空格
#多行注释,三个 """。
poem = """
\t The 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 #数字运算后的值 赋给变量 five
print(f"This shoulu be five: {five}") #输出格式化字符串
def secret_formula(started): #定义函数,名为secret_formula
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) #解包,赋值3个。
#remeber that this is another way to format a string
print("With a starting point of:{}".format(start_point))
#it's just like with an f"" string
print (f"We'd have {beans} beans, {jars} jars, and {crates} crates .")
start_point = start_point /10 #赋予变量
print("We can also do that this way :") #打印字符串
formula = secret_formula(start_point) #函数3个返回值赋给formula,后用*format 字符串格式化
#This is an easy way to apply a list to a format cooked_string
print("We'd have {} beans,{} jars, and {} cratess.".format(*formula))
PS C:\Users\WU\pyfile> python ex24.py
Let's practice everying
You'd need to know 'bout escape 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 shoulu be five: 5
With a starting point of:10000
We'd have 5000000 beans, 5000.0 jars, and 50.0 crates .
We can also do that this way :
We'd have 500000.0 beans,500.0 jars, and 5.0 cratess.
复习点
- 字符串格式化的两种常用格式:f" “、” ".format( )。
- 局部变量和全局变量的概念。函数内部的变量都是临时的,函数结束后变量被释放,函数内部的变量在函数外是没法使用的,可以算是一个封闭的环境。
- 1-12行:转义符\n 换行,\t = Tabs,’=’,\=,多行注释"""。
- 12-40:函数定义,return返回,字符格式化,解码。
习题25:更多更多的练习
代码
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ') #使用split方法,指定分隔符对字符串分割并返回一个列表。
return words
def sort_words(words):
""" Sorts the word."""
return sorted (words) #对列表中的元素按字母顺序升序排列,并且返回一个新的列表。
def print_first_word(words):
"""Prints the first word after popping it off."""
word = words.pop(0) #使用pop(0)方法拿出列表中第一个元素,并返回该元素的值。
print(word)
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1) #使用pop(-1)方法拿出列表最后一个元素,并返回该元素的值。
print(word)
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence) #结合break_words和sort_words
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence"""
words = break_words(sentence) #调用break_words和print_first_word、print_last_word
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence): #调用sort_sentence和print_first_word、print_last_word
"Sorts the words then prints the first and last one."
words = sort_sentence(sentence) #调用sort_sentence和print_first_word、print_last_word
print_first_word(words)
print_last_word(words)
PS C:\Users\WU\pyfile> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good tihngs come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'tihngs', 'come', 'to', 'those', 'who', 'wait.']
>>> sorted_words = ex25.sort_words(words)
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'tihngs', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sorted_words)
All
>>> ex25.print_last_word(sorted_words)
who
>>> sorted_words
['come', 'good', 'those', 'tihngs', 'to', 'wait.']
>>> sorted_words =ex25.sort_sentence(sentence)
>>> sorted_words
['All', 'come', 'good', 'those', 'tihngs', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
使用from ex25 import *
PS C:\Users\WU\pyfile> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32'
Type "help", "copyright", "credits" or "license" for more information.
>>> from ex25 import *
>>> sentence = "All good tihngs come to those who wait."
>>> words =break_words(sentence)
>>> words
['All', 'good', 'tihngs', 'come', 'to', 'those', 'who', 'wait.']
知识点
- split(’ ‘),’'号中间是空格,记得敲空格,相当于用空格去分开。
- 使用help(模块)得到模块帮助文档时是在python环境中的,而不是在shell中直接help。所以先在shell中打开py,然后再打开帮助文档。帮助文档就是定义函数或者类的三引号"""之间的字符串,称为documentation comments(文档注解)。导入文件时不需要.py的后缀,py知道文件是.py结尾的。所以只需要import ex25。
PS C:\Users\WU\pyfile> python
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> help(ex25)
Help on module ex25:
NAME
ex25
FUNCTIONS
break_words(stuff)
This function will break up words for us.
print_first_and_last(sentence)
Prints the first and last words of the sentence.
print_first_and_last_sorted(sentence)
Sorts the words then prints the first and last one.
print_first_word(words)
Prints the first world after popping it off
print_last_word(words)
Prints the first word after popping it off.
sort_sentence(sentence)
Takes in a full sentence and returns the sorted words.
sort_words(words)
Sorts the words.
FILE
c:\users\wu\pyfile\ex25.py
>>> help(ex25.break_words)
Help on function break_words in module ex25:
break_words(stuff)
This function will break up words for us.
- 使用import引入函数库有两种方式,但对函数的使用方式略有不同。
- 第一种引入函数库的方法如下:
Import <库名>
此时,程序可以调用库名中的所有函数,使用库中的函数的格式如下
<库名>.<函数名>(<函数参数>) - 第二种引入函数库的方法如下:
from <库名> import <函数名,函数名,…,函数名>
from <库名> import *
其中,*是通配符号,代表所有函数。
- 第一种引入函数库的方法如下:
- 使用代码文件就是跳到了代码文件的函数的地址运行函数然后跳回来。
- ls.pop(i) 作用:将列表中ls中第i项元素取出并且删除该元素。
- return和print毫无关系。基本思路是:函数通过参数接受输入,通过return返回输出。Print只是在终端打印输出而已。