Python基础 第5章 条件、循环及其他语句(1)

1. print和import

1.1 打印多个参数

 可用 + 连接多个字符串,可保证被连接字符串前无空格;

可用sep=“_”,自定义各种分隔符;

1 print("I","wish","to","register","a","complaint",sep="_")
2 结果:
3 I_wish_to_register_a_complaint

可自定义结束字符串,以替换默认的换行符;

1 print('Hello,',end='')
2 print('World!')
3 结果:
4 Hello,World!

1.2 导入时重命名

导入某个模块时,通常使用如下方式:

1 方法1:import somemodule
2 方法2:from somemodule import somefunction
3 方法3:from somemodule import somefuction,anotherfunction,yetanotherfunction
4 方法4:from somemodule import *

如果导入的两个模块,都包含同一个函数,可用按如下方法调用函数:

1 module1.open(...)
2 module2.open(...)
也可以在语句末尾加as子句并指定别名
3 import math as foobar
4 foobar.sqrt(4)

 

2. 赋值

 2.1 序列解包(可迭代对象解包)

将一个序列(或任何可迭代对象)解包,并将得到的值存储在一系列变量中。解释如下:

1 values = 1,2,3
2 print(values)
3 x,y,z = values
4 print(x)
5 结果:
6 (1, 2, 3)
7 1

(1)同时(并行)给多个变量赋值

1 x,y,z = 1,2,3
2 print(x,y,z)
结果:
1 2 3

(2)交换多个变量的值

1 x,y,z = 1,2,3
2 x,y = y,x
3 print(x,y,z)
4 结果:
5 2 1 3

*** 序列解包,在使用返回元组(或其他序列或可迭代对象)的函数或方法时很有用。

eg:随机从字典中获取或删除一个键-值对,用方法popitem,它随机获取一个键-值对并以元组的方式返回。然后将返回的元组解包到两个变量中。

1 scoundre = {'name':'Robin','girlfriend':'Marion'}
2 key, value = scoundre.popitem()
3 print(key)
4 print(value)
5 结果:
6 girlfriend
7 Marion

(3)用星号运算符(*)收集多余的值,这样无需确保值和变量的个数相同

 1 a,b,*rest = [1,2,3,4,5]
 2 print(rest)
 3 结果:
 4 [3, 4, 5]
 5 
# 带星号的变量可以放在其他位置 6 name = "Albus Precival Wulfric Brain Dumbledore" 7 first, *middle, last = name.split() 8 print(middle) 9 结果: 10 ['Precival', 'Wulfric', 'Brain']

赋值语句的右边可以是任何类型的序列,但带星号(*)的变量最终包含的总是一个列表。

1 a, *b, c = "abc"
2 print(a,b,c)
3 结果:
4 a ['b'] c

(4)链式赋值

用于将多个变量关联到同一个值,链式赋值是一种快捷方式。

1 x = y = somefunction()
2 
3 # 上述代码与下面等价
4 y = somefunction
5 x = y

(5)增强赋值

 如代码 x = x + 1,可直接将右边表达式中的运算符(+)移到赋值运算符(=)前面,写成 x += 1。该方式称为增强赋值,适用于所有标准运算符。增强赋值,可让代码更紧凑、更简洁,增加可读性。

 

3. 代码块 - 缩进

 代码块是通过缩进代码(即前面加空格)来创建的。

也可使用制表符,但标准做法是只使用空格来缩进,且每级缩进4个空格。

 

4. 条件和条件语句

(1) False,None,0,"",(),[],{},这些值均将被解释器视为假。

(2)if语句

(3)else子句

(4)elif子句

(5)代码块嵌套

 

5. 循环

 (1)while循环

1 name = ''
2 while not name:
3     name = input('plz enter your name:')
4 print('Hllo, {}!'.format(name))
5 结果:
6 plz enter your name:elon
7 Hllo, elon!

并未像书中所说:回车后再次出现提示信息。

书中修复该现象方法:将while not name 改为 while not name or name.isspace()或while not name.strip()。

(2)for 循环

该函数,可为序列(或其他可迭代对象)中每个元素执行代码块。基本上,可迭代对象是可使用for循环进行遍历的对象。

1 words = ['this','is','an','ex','parrot']
2 for word in words:
3     # 用end=' '替代print默认输出的换行符合
4     print(word, end=' ')
5 结果:
6 this is an ex parrot 

只要能使用for循环,就不用使用while循环!!!

创建范围函数range(0,10),起始位置为0,不包含结束位置(10)

1 print(list(range(0,10)))
2 结果:
3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

(3)迭代字典

  1)遍历字典的所有关键字

1 d = {'x':1,'y':2,'z':3}
2 for key in d:
3     print(key,end=', ')
4     print(key, 'corresponds to', d[key])
5 结果:
6 x, x corresponds to 1
7 y, y corresponds to 2
8 z, z corresponds to 3

  2)遍历字典的所有值,d.values()

1 for value in d.values():
2     print(value)
3 结果:
4 1
5 2
6 3

  3)遍历字典,返回键-值对,d.items()

1 for key,value in d.items():
2     print(key, 'corresponds to', value)
3 结果:
4 x corresponds to 1
5 y corresponds to 2
6 z corresponds to 3

***字典元素的排列顺序不确定,如果所处理的键或值顺序非常重要,可将键或值存储在一个列表中,并对列表排序,再迭代。

(4)迭代工具

  1)并行迭代 - zip内置函数,缝合序列

  如,需同时迭代两个序列,方法(1)如下:

 1 names = ['anne','beth','george','damon']
 2 ages = [12,45,32,99]
 3 
 4 for i in range(len(names)):
 5     print(names[i], 'is', ages[i], 'years old')
 6 结果:
 7 anne is 12 years old
 8 beth is 45 years old
 9 george is 32 years old
10 damon is 99 years old

  方法(2):用zip函数解包

 1 names = ['anne','beth','george','damon']
 2 ages = [12,45,32,99]
 3 
 4 #用zip缝合两个序列
 5 ziptool = list(zip(names,ages))
 6 print(ziptool)
 7 #缝合后,在循环中将元组解包
 8 for name,age in zip(names,ages):
 9     print(name, 'is', age, 'years old')
10 结果:
11 [('anne', 12), ('beth', 45), ('george', 32), ('damon', 99)]
12 
13 anne is 12 years old
14 beth is 45 years old
15 george is 32 years old
16 damon is 99 years old

  ***函数zip可用于“缝合”任意数量的序列

  ***使用zip函数缝合时,当序列长度不同时,函数zip将在最短的序列用完后停止“缝合”

1 listzip = list(zip(range(5), range(1000)))
2 print(listzip)
3 结果:
4 [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

  2)迭代时获取索引

  使用内置函数enumerate,该函数能迭代索引-值对,其中的索引是自动提供的。

 1 names = ['anne','beth','george','damon']
 2 print(enumerate(names))
 3 
 4 for index,string in enumerate(names):
 5     if 'geo' in string:
 6         names[index] = '[censored]' # 将包含'geo'的元素替换为'[censored]'  
7
print(string,'\'s index is', index)
8

9 print(names)
10
11 结果:
12 <enumerate object at 0x000001C7EC6F3E58>
13 george 's index is 2
14
15 ['anne', 'beth', '[censored]', 'damon']

  3)反向迭代和排序后再迭代

 1 lists = [4, 3, 5, 8, 6, 7]
 2 print(sorted(lists))
 3 print(list(reversed(lists)))
 4 结果:
 5 [3, 4, 5, 6, 7, 8]
 6 [7, 6, 8, 5, 3, 4]
 7 
 8 words = 'Hello, world!'
 9 print(sorted(words))
10 结果:
11 [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
12 
13 print(list(reversed(words)))
14 reversed_words = ''.join(reversed(words))
15 print(reversed_words)
16 结果:
17 ['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
18 !dlrow ,olleH
19 
20 # reversed和sorted,不会就地修改对象,而是返回反转和排序后的版本
21 print(words)
22 结果:Hello, world!

*** 要按字母表排序,可先转换为小写。可将sort或sorted的key参数设置为str.lower

1 print(sorted("aBC", key=str.lower))
2 结果:
3 ['a', 'B', 'C']

(5)跳出循环

   1)break - 结束(跳出)循环

1 from math import sqrt
2 
3 for n in range(99, 0, -1):
4     root = sqrt(n)
5     if root == int(root):
6         print(n)
7         break
8 
9 结果:81

  2)continue

  结束当前迭代,并跳到下一次迭代开头(跳过循环体中余下语句,但不结束循环)。

  continue不如break用得多。

  3)while True/break

  while True导致循环永不结束,但将条件放在了循环体内的一条if语句中,而这条if语句将在条件满足时调用break。(避免在代码中过多使用break)

1 while True:
2     word = input('please enter a word: ')
3     if not word:
4         break
5     print('The word is ', word)
6 结果: 7 please enter a word: elon 8 The word is elon 9 please enter a word:

(6)循环中的else子句

  通常,循环中使用break是因为“发现”了什么或“出现”了什么情况。若要判断循环是提前结束还是正常结束:

  1)可在循环开始前定义一个布尔变量并将其设置为False,再在跳出循环时设置为True。便可在循环后用一条if语句来判断循环是否提前结束。

 1 from math import sqrt
 2 break_out = False
 3 for x in range(99,81,-1):
 4     root = sqrt(x)
 5     if root == int(root):
 6         break_out = True
 7         print(x)
 8         break
 9 if not break_out:
10     print("I don't break out!")
11 结果:
12 I don't break out!

  模板:

 1 # 模板
 2 break_out = False
 3 for x in seq:
 4     do_something()
 5     if condtion(x):
 6         break_out = True
 7         break
 8     do_something_else()
 9 if not break_out:
10     print("I don't break out!")

  2)***简单的方法,在循环中添加一条else子句,它仅在没有调用Break时才执行。

 1 from math import sqrt
 2 for n in range(99,81,-1):
 3     root = sqrt(n)
 4     if root == int(root):
 5         print(n)
 6         break
 7 else:
 8     print("Don't find it!")
 9 
10 结果:Don't find it!

20190830

  治军之道,以勤字为先。身勤则强,佚则病;家勤则兴,懒则衰;国勤则治,怠则乱;军勤则胜,惰则败。惰者,暮气也,常常提其朝气为要。——曾文正公,巳未二月

 

posted @ 2019-08-15 08:53  ElonJiang  阅读(254)  评论(0编辑  收藏  举报