四. input 读取输入值
在Python 2.x版本中,使用raw_input,但是到了Python 3.x,转变成input,帮助文档对该方法的说明如下:
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
Example:
>>> s = input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
4.1. 输入字符串
nID = ''
while 1:
nID = input("Input your id plz:\n")
if len(nID) != len("123456789"):
print('wring length of id,input again')
else:
break
print('your id is %s' % (nID))
4.2.输入整数
nAge = int(input("input your age plz:\n"))
if nAge > 0 and nAge < 120:
print('thanks!')
else:
print('bad age')
print( 'your age is %d\n' % nAge)
4.3. 输入浮点型
fWeight = 0.0
fWeight = float(input("input your weight: \n"))
print('your weight is %f' % fWeight)
4.4. 输入16进制数据
nHex = int(input('input hex value(like 0x20):\n'),16)
print( 'nHex = %x,nOct = %d\n' %(nHex,nHex))
4.5. 输入8进制数据
nOct = int(input('input oct value(like 020):\n'),8)
print ('nOct = %o,nDec = %d\n' % (nOct,nOct))
五. Enumerate 用法
帮助文档说明:
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable. enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2, seq[2]), ....
For example:
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
... print(i, season)
0 Spring
1 Summer
2 Fall
3 Winter
5.1 在for循环中得到计数
参数为可遍历的变量,如 字符串,列表等;返回值为enumerate类:
import string
s = string.ascii_lowercase
e = enumerate(s)
print(s)
print(list(e))
输出为:
>>>
abcdefghijklmnopqrstuvwxyz
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j'), (10, 'k'), (11, 'l'), (12, 'm'), (13, 'n'), (14, 'o'), (15, 'p'), (16, 'q'), (17, 'r'), (18, 's'), (19, 't'), (20, 'u'), (21, 'v'), (22, 'w'), (23, 'x'), (24, 'y'), (25, 'z')]
>>>
在同时需要index和value值的时候可以使用 enumerate。
5.2 enumerate 实战
line 是个 string 包含 0 和 1,要把1都找出来:
#方法一
def read_line(line):
sample = {}
n = len(line)
for i in range(n):
if line[i]!=?':
sample[i] = int(line[i])
return sample
#方法二
def xread_line(line):
return((idx,int(val)) for idx, val in enumerate(line) if val != ?')
print( read_line(�'))
print( list(xread_line(�')))
六. yield 用法
The yield expression is only used when defining a generator function, and can only be used in the body of a function definition. Using a yield expression in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of a generator function. The execution starts when one of the generator’s methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of expression_list to generator’s caller. By suspended we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack. When the execution is resumed by calling one of the generator’s methods, the function can proceed exactly as if the yield expression was just another external call. The value of the yield expression after resuming depends on the method which resumed the execution.
All of this makes generator functions quite similar to coroutines; they yield multiple times, they have more than one entry point and their execution can be suspended. The only difference is that a generator function cannot control where should the execution continue after it yields; the control is always transferred to the generator’s caller.
The yield statement is allowed in the try clause of a try ... finally construct. If the generator is not resumed before it is finalized (by reaching a zero reference count or by being garbage collected), the generator-iterator’s close() method will be called, allowing any pending finally clauses to execute.
yield 简单说来就是一个生成器,生成器是这样一个函数,它记住上一次返回时在函数体中的位置。对生成器函数的第二次(或第 n 次)调用跳转至该函数中间,而上次调用的所有局部变量都保持不变。
(1)生成器是一个函数:函数的所有参数都会保留
(2)第二次调用 此函数 时:使用的参数是前一次保留下的.
(3)生成器还“记住”了它在流控制构造:生成器不仅“记住”了它数据状态。 生成器还“记住”了它在流控制构造(在命令式编程中,这种构造不只是数据值)中的位置。由于连续性使您在执行框架间任意跳转,而不总是返回到直接调用者的上下文(如同生成器那样),因此它仍是比较一般的。 http://www.csvt.net/
yield 生成器的运行机制
当问生成器要一个数时,生成器会执行,直至出现 yield 语句,生成器把 yield 的参数给你,之后生成器就不会往下继续运行。当你问他要下一个数时,他会从上次的状态开始运行,直至出现yield语句,把参数给你,之后停下。如此反复直至退出函数。
6.1 Yield 应用
#生成全排列
def perm(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p
#生成组合
def comb(items, n=None):
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[i+1:]
for c in comb(rest, n-1):
yield v + c
a = perm('abc')
for b in a:
print(b)
break
print('-'*20)
for b in a:
print(b)
a = perm('abc')
for b in a:
print(b)
break
print('-'*20)
for b in a:
print(b)
执行结果:
abc
--------------------
acb
bac
bca
cab
cba
abc
--------------------
acb
bac
bca
cab
cba
在第一个循环break后,生成器没有继续执行,而第二个循环接着第一个循环执行
Python 基础语法知识(二)
精选 转载上一篇:Python 基础语法知识(一)
下一篇:Python 基础语法知识(三)
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
Python基础知识-5
介绍python的各种应用实例
python -
Python基础语法(二)
条件判断比如,输入价格,根据价格打印不同的内容,在Python程序中,用if语句实现:price = 21if price > 20: #注
python 算法 数据结构 if语句 Python -
python基础知识——基本语法
在python基础知识这个系列中
python 下划线 缩进 -
Python的基础语法(二)
Tuple数据类型: 字典的应用: 运行的效果图: 函数:
默认参数 python 调用函数 -
rust基础语法知识
文章目录一. slice二. 引用& /借
ipad 字段 作用域 -
Javascript知识【基础语法】
JavaScript基础语法,入门案例,JS常见三大框架,JS引入,猜数字小游戏
java javascript html 随机数 -
python基础知识---简单语法
《python基础语法》
python 简单语法 -
【Python学习】—Python基础语法(二)
作用:注释不是程序,不能被
python 学习 android 字符串 字面量