核心语言学无编程基础入门Python(第五章)

建议先看完前面的章节,前面章节内容:

  1. 和Python好好谈一谈(print)
  2. Python你帮我省省心啊(=)
  3. 把文字扭一扭(关于string的命令)
  4. 让别人也来参与一下(raw_input)
  5. 我真得不想看大段的字串啊!(list的概念)
  6. 原来都是烤串儿而已(slicing/indexing)
  7. 串儿上的肉要一块一块地吃(for … in …)

8 我就问一次,如果…(if)

从这章开始,叙事会变得非常例行公事。因为读到这里的人,概念已经有一些了,最多只是说说功能。

之前说到for … in …指的是把一个「串」从头读到尾。可是这种命令缺少一个【在读的过程中进行选择的能力】。比如在之前的实战练习里,要计算特定元音在每一个单词里出现的次数(脚本1)。

[code language=”python”]
#脚本1
#输入文本,稍微整理一下#
text="Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability."
text_cl=text.lower().replace(‘,’,”).replace(‘.’,”)
words=text_cl.split()
#问下用户想查哪个元音#
print ‘You are reading the following text:\n’
print text+’\n’
vowel=raw_input(‘Which vowel is in your mind? ‘)
#按顺序读一个,找一个,print一个#
for word in words:
rst=str(word.count(vowel))
print word+’\t’+rst
[/code]

脚本1运行的结果是:如果这个单词不包含这个元音,显示0;如果这个单词包含这个元音,则显示此元音在这个单词里出现过几次。这个脚本有一个很明显的缺点,那就是【不管包不包含这个元音,结果总会占用一行】。所以如果文本的长度再大些,基本一个屏幕就显示不出来了。

Python提供的解决方案是 if 的条件,句法是:

[code language=”python”]
if 如果某个测试成功了:
做些什么
[/code]

还有一个可选的else功能,指的是如果不是这么回事,则做另外一件事情。(else的好处是条件不用再打了…只要if不成立就行了),比如脚本2:

[code language=”python”]
#脚本2:
a=int(raw_input("what is a? "))
b=int(raw_input("what is b? "))
if a>b:
print "a is greater than b"
else:
print "a is not greater than b"
[/code]

这个脚本让用户输入两个数字,比较它们的大小(注意用户输入的东西一开始是字串,要转成数字之后才能比较大小)。

另外还有一个可选的elif,意思是如果一开始的if那里测试失败了,可以再测一下elif这边(如果还是失败了,才去else那里。当然了elif这种「备胎」可以有很多个。)比如脚本3:

[code language=”python”]
a=int(raw_input("what is a? "))
b=int(raw_input("what is b? "))
if a>b:
print "a is greater than b"
elif a==b:
print "a equals b"
else:
print "a is less than b"
[/code]

上面的脚本看上去都超简单,但实际上有点麻烦,因为所谓if【测试成功】有很多种情况:

【数字】去比大小成功了是一种,但除了之前有提到的大于(>),小于(<),等于(==)以外,其实还有其他的一些(注:=的功能是赋值,不是比大小): x>=y x大于或等于y
x<=y x小于等于y
x!=y x不等于y

两个【字串】、或两个【列表】是不是相同的,或者某个「串」里是不是包含某个元素,都能拿来做测试:

x is y 如果x和y是相同的
x is not y 如果x和y是不同的
x in y 如果x是y中的一个元素
x not in y 如果x不是y中的一个元素

【还有一种】、并且可能更常用也更方便,是【直接去测试一个变量】,只要这个变量不是空字串''、不是空列表[],不是数字0,不是None不是False这些……等等等等……就算测试成功。比如脚本4里的if测试,只要用户输入的是除了0以外的任意一个数字,Python读到这一行自动就测试成功。

[code language="python"]
#脚本4:
a=float(raw_input("gimme a number: "))
if a:
print "approved"
[/code]

对了测试的时候也可以加入and, or, and not 这种组合。


9 你慢慢吃吧,只要还有剩的(while)

if 的特点是【只测试一次,测试成功之后就执行定义好的事情】,测试不成功就直接去下一行(elif也好,else也好)。这种工作模式的缺点在于无论测试的条件订得多么精巧、详细,可是定义好的事情只会被执行一次。任务打字打了很久最后只被执行一次明显很不划算,于是就有了while循环,它做的事情是【如果测试成功,完成定义好的事情,之后重新检验重新干活直到检验失败为止】。

句法上来说和if的命令是完全一样的(脚本5):

[code language="python"]
#脚本5:
a=1
while a<5:
print "a is "+str(a)+" and a is less than 5"
[/code]

不过脚本5运行起来是个死循环,while也是最容易出现死循环的。while容易出现死循环的原因在于【定义的事情,必须在重复若干次之后,可以让while本身的测试失败】。在脚本5的while循环里,Python只作了print这一件事情,而这件事情对于while的验证不会产生任何影响。这时需要记住Ctrl+C是最好的朋友,可以用来手动中断脚本的。脚本6则是可行的。

[code language="python"]
#脚本6
a=1
while a<5:
print "a is "+str(a)+" and a is less than 5"
a=a+1
[/code]

while经常被用来做计数器,让特定的命令被执行若干次,比如算一下2的整数次方(脚本7),只要计数器cnt的数字没有达到用户希望的次数,while循环里的计算不会停下来。(对了,a=a+1可以简化为 a+=1)

[code language="python"]
#脚本7
cnt=1
tm=int(raw_input("2 to the power of ___? "))
rst=2
while cnt<tm:
rst=rst*2
cnt+=1
print rst
[/code]

实战中如果同时用上while和if,可以做很多事情。【比如有一篇文章,我们可以找一下这篇文章里元音出现过五次或五次以上的词】。

[code language="python"]
#脚本8
#输入文本,稍微整理一下#
text="Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java. The language provides constructs intended to enable clear programs on both a small and large scale. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library. Python interpreters are available for installation on many operating systems, allowing Python code execution on a wide variety of systems. Using third-party tools, such as Py2exe or Pyinstaller, Python code can be packaged into stand-alone executable programs for some of the most popular operating systems, allowing the distribution of Python-based software for use on those environments without requiring the installation of a Python interpreter. CPython, the reference implementation of Python, is free and open-source software and has a community-based development model, as do nearly all of its alternative implementations. CPython is managed by the non-profit Python Software Foundation."
text_cl=text.lower().replace(',','').replace('.','')
words=text_cl.split()
#问用户哪些字母可以代表元音#
print 'You are reading the following text:\n'
print text+'\n'
vowels=raw_input('Which letters do you consider as vowels?')
vList=[]
for vowel in vowels:
if vowel.lower() not in vList:
vList.append(vowel.lower())
#测试words里每一个单词#
wfList=[]
while words:
word=words.pop(0)
vC=0
for vowel in vList:
vC+=word.count(vowel)
if vC>=5:
wfList.append(word+"\t"+str(vC))
for p in wfList:
print p
[/code]

下一章估计是最后一章了。


小抄:if,elif,else,while

 

ynshen