Python入门(5):条件、循环和其他语句

两年前学习了《Python基础教程》的前4章,因为看到python的条件、循环语句和c++、Matlab等很相似,于是就没再整理下去。既然最近又把python翻出来了(电脑上一直装着),那就继续吧。从零开始,学习基础。

 

1、关于print,使用逗号输出

print('Age:',42)                    #Age: 42
print(1,2,3)                        #1 2 3
print((1,2,3))                      #(1, 2, 3)
name='Gumby'
salutation='Mr.'
greeting='Hello,'
print(greeting,salutation,name)     #Hello, Mr. Gumby
greeting='Hello'
print(greeting+',',salutation,name) ##Hello, Mr. Gumby

2、关于import

从模块导入函数,可以使用:

import 模块

或 from 模块 import 函数

或 from 模块 import 函数1,函数2,函数3

或 from 模块 import *

只有确定自己想要从给定的模块导入所有功能时,才使用最后一个版本。

若两个模块都有open函数,则用第一种方式导入,然后这样使用函数:模块1.open(),模块2.open()。也可以这样:

from 模块1 import open as open1

from 模块2 import open as open2

这是在语句末尾增加一个as子句,在as后给出想要使用的别名,可以为整个模块提供别名,也可以为函数提供别名。

import math as foobar
print(foobar.sqrt(4))               #2.0
from math import sqrt as foobar
print(foobar(4))                    #2.0

3、关于赋值

1)序列解包

多个赋值操作可同时进行,用它交换两个或多个变量也是可以的。这叫做序列解包(sequence unpacking)或递归解包,即将多个值的序列解开,然后放到变量的序列中。

x,y,z=1,2,3
print(x,y,z)                        #1 2 3
x,y=y,x
print(x,y,z)                        #2 1 3

当函数或者方法返回元组时,序列解包尤其有用。假设需要获取(和删除)字典中任意的键-值对,可使用popitem方法,这个方法将键-值对作为元组返回。

scoundrel={'name':'Robin','girlfriend':'Marion'}
key,value=scoundrel.popitem()
print(key)                          #name
print(value)                        #Robin

注意,所解包的序列中的元素数量必须和放置在赋值符号(=)左边的变量数完全一致,否则Python会在赋值时引发异常。不过,可以像在函数的参数列表中一样使用星号运算符。使用星号的变量也可放在第一个位置,这样它就总会包含一个列表。

a,b,*rest=[1,2,3,4]
print(rest)                         #[3, 4]

2)链式赋值:把同一个值赋给多个变量

x=y=1
print(x,y)                          #1 1

3)增量赋值:对于+、*、\、%等标准运算符都适用

x=2
x+=1
x*=2
print(x)                            #6
fnord='foo'
fnord+='bar'
fnord*=2
print(fnord)                        #foobarfoobar

4、语句块

块中的每行都应该缩进同样的量。Python中,冒号(:)用来标识语句块的开始,块中的每个语句都是缩进的(缩进量相同)。当回退到和已经闭合的块一样的缩进量时,就表示当前块结束。

5、布尔表达式

False    None    0    ""    ()    []    {}  作为布尔表达式时,会被解释器看作假(false),即:标准值False和None、所有类型的数字0(包括浮点型、长整型和其他类型)、空序列(比如空字符串、空元组、空列表)以及空字典都为假。其他的一切都被解释为真,包括特殊值True。

注意,尽管[]和""都是假值(即:bool([])==bool("")==False),但是它们本身不相等(即:[]!="")。对于其他不同类型的假值对象也是如此(e.g. ()!=False)。

可以用and, or和not这三个运算符来连接布尔表达式。

True==1                             #True
False==0                            #True
True+False+42                       #43
bool('')                            #False
bool(0)                             #False
bool([]!="")                        #True

6、条件和条件语句

(1)if语句,实现条件执行。即:如果条件(if和冒号之间的表达式)判定为真,那么后面的语句块就会被执行;如果条件为假,则语句块不被执行。

(2)else子句,上面的条件为假时执行的语句块。

(3)elif子句,是“else if”的简写,用于有多个条件。

(4)嵌套if语句。

# if语句
num=int(input('Enter a number:'))
if num>0:
    print('The number is positive')

# else子句
num=int(input('Enter a number:'))
if num>0:
    print('The number is positive')
else:
    print('The number is not positive')

# elif子句
num=int(input('Enter a number:'))
if num>0:
    print('The number is positive')
elif num<0:
    print('The number is negative')
else:
    print('the number is zero')

# 嵌套if语句
num=int(input('Enter a number:'))
if num!=0:
    if num>0:
        print('The number is positive')
    else:
        print('The number is negative')
else:
    print('the number is zero')

(5)表达式有:x==y, x<y, x>y, x>=y, x<=y, x!=y, x is y, x is not y, x in y, x not in y. 其中,==运算符是判定两个对象是否相等;is运算符是判定同一性而不是相等性。

x=y=[1,2,3]
z=[1,2,3]
x==y                                #True
x==z                                #True
x is y                              #True
x is z                              #False

(6)assert断言:如果知道必须满足特定条件,程序才能正确运行,可在程序中添加assert语句充当检查点,还可在条件后添加字符串,用来解释断言。

age=-1
assert 0<age<100, 'The age must be realistic'

7、循环

(1)while循环

x=1
while x<=100:
    print(x)
    x+=1                            #输出1,2,3,...,100.

for number in range(1,101):
    print(number)                   #也是输出1,2,3,...,100.

name=''
while not name:
    name=input('Please enter your name:')
print('Hello, %s' %name)            #Hello, Nina

name=''
while not name.strip():             #空格字符串判定为假
    name=input('Please enter your name:')
print('Hello,{}!'.format(name))     #Hello,Nina!

(2)for循环

words=['this','is','an','ex','parrot']
for word in words:
    print(word)
#this
#is
#an
#ex
#parrot

numbers =[0,1,2,3]
for number in numbers:
    print(number)
#0
#1
#2
#3

(3)迭代字典

d={'x':1,'y':2,'z':3}
for key in d:
    print(key,'corresponds to',d[key])
#y corresponds to 2
#z corresponds to 3
#x corresponds to 1
for key,value in d.items():
    print(key,'corresponds to',value)
#输出同上

(4)迭代工具:python提供了多个可帮助迭代序列(或其他可迭代对象)的函数(见Chapt10的itertools),以及一些内置函数。

① 内置函数zip:用于将序列“缝合”起来,并返回一个由元组组成的序列。当序列长度不等时,以最短的序列进行“缝合”。

names=['aa','bb','cc','dd']
ages=[12,17,36,30]
for i in range(len(names)):
    print(names[i],'is',ages[i],'years old')
#aa is 12 years old
#bb is 17 years old
#cc is 36 years old
#dd is 30 years old
list(zip(names,ages))               #[('aa', 12), ('bb', 17), ('cc', 36), ('dd', 30)]
for name,age in zip(names,ages):
    print(name,'is',age,'years old')
#aa is 12 years old
#bb is 17 years old
#cc is 36 years old
#dd is 30 years old

list(zip(range(5),range(1000)))     #[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

② 内置函数enumerate:获取当前对象的索引,替换一个字符串列表中所有包含子串'xxx'的字符串。

strings=['China','is','a','country','with','a','very','long','histry']
index=0
for string in strings:
    if 'a' in string:
        strings[index]='[a]'
    index+=1
print(strings)
#['[a]', 'is', '[a]', 'country', 'with', '[a]', 'very', 'long', 'histry']

strings=['China','is','a','country','with','a','very','long','histry']
for index,string in enumerate(strings):
    if 'a' in string:
        strings[index]='[a]'
print(strings)
#['[a]', 'is', '[a]', 'country', 'with', '[a]', 'very', 'long', 'histry']

③ 内置函数reverse和sort:反向迭代和排序后再迭代。

sorted([4,3,6,8,3])                 #[3, 3, 4, 6, 8]
sorted('Hello,world!')              #['!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
list(reversed('Hello,world!'))      #['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'H']
''.join(reversed('Hello,world!'))   #'!dlrow,olleH'
sorted('aBC',key=str.lower)         #['a', 'B', 'C']

(5)跳出循环

无论是for循环还是while循环,都可使用continue、break和else子句。

① break:直接跳出循环

# 找出小于100的最大平方值后直接跳出循环
from math import sqrt
for n in range(99,0,-1):
    root=sqrt(n)
    if root ==int(root):
        print(n)
        break
#81

② continue:结束当前迭代,跳到下一次迭代开头。即:跳过循环体中余下的语句,但不结束循环。

③ while True/break:循环永不结束,将条件放在循环体内的一条if语句中,当这条if语句条件满足时调用break。

while True:
    word=input('Please enter a word:')
    if not word: break
    print('The word was ',word)

(6)循环中的else子句

from math import sqrt
for n in range(99,81,-1):
    root=sqrt(n)
    if root==int(root):
        print(n)
        break
else:
    print("Didn't find it!")
#Didn't find it!

8、简单推导

[x*x for x in range(10)]            #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[x*x for x in range(10) if x%3==0]  #[0, 9, 36, 81]
[(x,y) for x in range(3) for y in range(3)] #[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

 #将名字首字母相同的男孩和女孩进行配对
 girls=['alice','bernice','clarice']
 boys=['chris','arnold','bob']
 [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
 #['chris+clarice', 'arnold+alice', 'bob+bernice']
 
# Another method:
letterGirls={}
for girl in girls:
    letterGirls.setdefault(girl[0],[]).append(girl)
print([b+'+'+g for b in boys for g in letterGirls[b[0]]])
#['chris+clarice', 'arnold+alice', 'bob+bernice']

9、pass、del、exec和eval

pass:用在什么都不做的if语句中。注:python中代码块不能为空。

del:删除不再使用的对象。e.g. del x.

exec:将字符串作为代码执行。多数情况,应传递命名空间(作用域),用于放置变量。exce什么都不返回。

eval:计算用字符串表示的python表达式的值,并返回结果。

exec("print('Hello, world!')")      #Hello, world!

from math import sqrt
scope={}
exec('sqrt=1',scope)
sqrt(4)                             #2.0
scope['sqrt']                       #1

 

以上。参考书是Magnus Lie Hetland著的《Python基础教程(第2版·修订版)》+《Python基础教程(第3版)》Chapter 5。

两年的时间,第三版也出版了,之后会以《Python基础教程(第3版)》为主。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值