版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_24994943/article/details/82016023
# ex24 更多的练习
print("Let's practice everything.")
# python的输出,转义字符的运用
print('You\'d need to know \'bout escapes with \\ that do:') # You'd need to know 'bout escapes with \ that do:
print('\n newlines 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.
"""
print("------------")
print(poem)
print("------------")
"""
The lovely world
with logic so firmly planted
cannot discern
the needs of lovely
nor comprehend passion from intuition
and requires an explanation
where there is none.
"""
# python函数的应用,返回值可以多个
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)
# python输出变量的方法一
print("With a starting point of: {}".format(start_point))
# python输出变量的方法二
print(f"We'd have {beans} beans, {jars} jars, and {crates} crates.")
start_point /= 10
print("We can also do that this way:")
# 用一个变量存储返回值
formula = secret_formula(start_point)
# python输出变量的方法三,将存有三个变量的变量逐个输出
print("We'd have {} beans, {} jars, and {} crates.".format(*formula))
# ex25 更多的练习
# 在命令行中运行python,然后导入该python文件(import ex25),即可使用以下这些函数
def break_words(stuff):
"""
This function will break up words for us.
这是一个文档注释,当我在命令行输入help(ex2.break_words)时
会显示函数名、参数以及此文档注释
"""
words = stuff.split(' ') # 将文本以空格分开成多个单词
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words) # 对单词进行排序
def print_first_word(words):
word = words.pop(0) # 取出第一个单词,此时words这个列表里会删除第一个单词
print(word)
def print_last_word(words):
word = words.pop(-1) # 取出最后一个单词,此时words这个列表里会删除最后一个单词
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)