笨方法学python笔记(3)

本文通过习题25介绍了Python编程中定义多个实用函数的方法,包括字符串拆分、单词排序及打印等,并探讨了如何在Python环境中通过交互式窗口调用这些函数,还讨论了在修改脚本后如何正确地更新并调用新增加的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

习题25之前几个习题主要是阅读别人写的代码,做好记录,然后记下来,虽然现在可能不太能理解一些语句,但是先过眼有个印象总归没有错。

习题25:老规矩,贴上自己敲出来的代码。敲代码的时候想练练打字,试试不看键盘盲打敲,给无聊枯燥的码代码带来一点乐趣。


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):
	"""Print thr 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(words)
	print_first_word(words)
	print_last_word(words)
	
def print_first_and_last_sorted(sentence):
	"""Sorts the words then print the first and last one."""
	words = sort_sentence(sentence)
	print_first_word(words)
	print_last_word(words)

这是一个由众多函数组成的脚本,根据教程,要求我们用交互式窗口调用这些函数。首先是import模组(module),这里有两个方法,一个是import 脚本名,一个是from 脚本名 import *。用前一种方法导入时,调用函数需要用脚本名.函数名;后一种方法是导入模组中的所有东西,因此在调用函数的时候可以直接用函数名,省去了多次使用脚本名的麻烦。


在做练习的时候,我加入了一个新函数,等到调用时却提示我“name 函数名 is not defined”,令人奇怪。后来查阅了一下资料,是因为import会生成一个.pyc的编译文件,当调用函数时,系统直接从.pyc的文件中调用函数,因此,尽管脚本改动了,但是.pyc文件并没有改动,仍是用的修改前的脚本内容,所以,需要重新加载脚本内容,用reload函数。


于是,试了一下reload函数。

在这里有一点要注意一下。如果先import 脚本名然后reload(脚本名),那么在调用函数的时候仍是用脚本名.函数名;如果先from 脚本名 import *,然后reload(脚本名),系统就会报错,提示“脚本名 is not defined”。如果觉得每次输入脚本名.函数名太麻烦了,那可以先用import 脚本名,然后reload (脚本名),最后再输入from 脚本名 import *。这个顺序不能颠倒,不然就会报错。如下是运行的结果,从图中可以得到印证。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值