Python关键字介绍和使用

本文记录了作者在春节期间因疫情居家期间学习Python的过程,涵盖了Python的基本关键字、面向对象编程、异常处理、模块导入等内容,并通过实际代码示例进行了详细解析。

最经新型冠状病毒非常严重,春节假期哪也去不了,索性就在家里稍微学习一下Python,毕竟乘着人工智能的浪潮Python已经非常流行了。同时工作中也需要修改编写Python脚本,更点燃学习Python的渴望。这里记录下学习笔记,有过面向对象,面向过程的编程经验,学习起来应该会快点。下面先列举出pytyon关键字,let’s go!

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

python版本:

D:\test\python>python --version
Python 2.7.10

1.and、print

这个和C语言的 “&&” 运算是一样的,只有and两边同时为TRUE时,表达式才为TRUE。

  • 怎么样算FALSE: 空列表:[]、空元组:()、空字典::{}、空字符串:’’或“”、零值:0
  • 怎么样算TRUE:除了上面的其它都为TRUE。

实例:

a = 1
b = 1
list = ['hello']
list1 = []

if a and b :
    print("hello world")

if list1 and a:
    print("list is no null")

if list:
    print("list is no null:--->%s" %list[0])
    del list[0]

if list is not None:
    print list
    print("empty list")

输出结果:

D:\test\python>python and.py
hello world
list is no null:—>hello
[]
empty list

上面可以看到and两边可以是列表,bool值,由此验证上面的两项。

2.exec

此关键字和linux shell中的exec同样类似,都是为了执行脚本命令而实现的。当需要动态执行python命令时,可以使用此命令

a = 2
b = 3
cmd = 'print(\'hello world\')'
exec(cmd)
cmd = 'print(\'a + b = %d\' %(a+b))'
exec(cmd)

结果:

D:\test\python>python exec.py
hello world
a + b = 5

3.not

此关键字可以理解成 “非” 的意思,类似于C语言中的 ‘!’ 所以用起来很容易理解。

a = 0
b = []
c = ('1')

if not a :
    print ('a is FALSE')
if not (a and len(b)) :
    print ("(a and len(b)) is 0")
if not len(b) :
    print ('list b is None')
if not len(c) :
    print("c is None")

输出not作用对象可以是一个bool值bool表达式。
输出结果:

D:\test\python>python not.py
a is FALSE
(a and len(b)) is 0
list b is None

4.assert、is

  • assert
    和其它编程语言一样,这里也是断言的意思。用于判断某一个条件是否达到预计条件。如果不满足的话,同样会抛出异常。
a = 66
b = ['55','armwind']
c = []
assert a > 44 and b
print a
assert len(b) is not 0
print ('len:%d' %len(b))
assert len(c) is not 0
print (c)

上面能够看到 assert后面是表达式,当然也可以是一个bool值。下面的结果可以看到,如果断言不满足时,会抛出断言错误。
结果:

66
len:2
Traceback (most recent call last):
File “assert.py”, line 8, in
assert len© is not 0
AssertionError

  • is:即为是的意思,上面例子可见。

5.finally

此关键字一般和try,except一起使用,从字面意思可以了解这里是最终的意思,就是最后都要执行的。这里就顺便一起总结下

  • 常用的异常
异常名称描述
AttributeError试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError输入/输出异常;基本上是无法打开文件
ImportError无法引入模块或包;基本上是路径问题或名称错误
IndentationError语法错误(的子类) ;代码没有正确对齐
IndexError下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError试图访问字典里不存在的键
KeyboardInterruptCtrl+C被按下
NameError使用一个还未被赋予对象的变量
SyntaxErrorPython代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError传入对象类型与要求的不符合
UnboundLocalError试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量导致你以为正在访问它
ValueError传入一个调用者不期望的值,即使值的类型是正确的
  • 例子
dat=['armwind1','armwind2']
dic={'name': 'armwind', 'age': 30}

try :
    print  dat[3]
    print dic['name1']
except IndexError as e:
    print('IndexError:%s' %e)
except KeyError as e:
    print('keyError:%s' %e)
except ValueError as e:
    print('ValueError:%s' %e)
finally :
    print("do something")

上面的异常中加入了2个异常,“IndexError”,“KeyError ”,但是只捕获到了第一个异常,由此可以看到,try…except只能捕获到第一个异常。例子中使用as关键字,打印出了异常。运行结果如下:

D:\test\python>python try.py
IndexError:list index out of range
do something

6.or

类似于C语言的 “||” 运算,例子就不多说了,通之前的and和not是一样的。

7.for、break、continue、in

同C语言中的break,continue作用一样,其中break跳出大循环体,continue跳出当前循环。for语句和C语言还是有些出入的,python中的可以遍历任何序列的数据,如一个列表或者一个字符串。

dat = 'cfj'
dic = ['armwind1','armwind2','armwind3']
for d in dat:
    print(d)
print('--------dic-----------')
for d in dic:
    print(d)
print('--------int-----------')
for i in range(1,20):
    if i == 6:
        break
    if i == 2:
        continue
    print(i)

从下面的结果可以看出for循环确实可以循环遍历字符串中的每一个字符,不过这样操作意义不大。一般都是循环遍历列表。
结果:

D:\test\python>python break.py
c
f
j
--------dic-----------
armwind1
armwind2
armwind3
--------int-----------
1
3
4
5

8.pass

pass字面意思就是什么都不做,相当于占位符。当我们定义了一个接口后,如果不实现的话则会报错,在方法中添加pass就不会报错了。

def test():

print("hello world")

上面如果不加pass的话,则会报下面的错误,加上就可以成功运行。

File “pass.py”, line 3
print(“hello world”)
^
IndentationError: expected an indented block

9.class、def、return

python中的class与其它面向对象的语言类似,不够python中一些命名需要注意下

  • this
    python中没有this指针,取而代之是self,在类形参里面第一个参数需要是 “self” 记住是这样写的即可。
  • 构造函数
    构造函数形如__init__(self,arg1,arg2,...),注意开始是 self
  • 析构函数
    构造函数形如__del_(self,arg1,arg2,...),注意开始是 self
  • 私有成员
    私有成员需要开始加入2个下划线 __param
  • 私有方法
    私有方法需要开始加入2个下划线 __func
  • 类的继承
    在声明类时,在类名后面添加对应父类名称即可。例如有父类father,则其子类为 class son(father):. 如果是多继承,则子类的为class son(father1, fater2): 如下面例子单继承object。
class human(object):
    def __init__(self, nam, ag, phone) :
        print("create human %s" %nam)
        self.name = nam
        self.age = ag
        self.__phone = phone

    def __set_phone(self, p):
        self.__phone = p

    def print_property(self) :
        print('name:%s, age:%d, phone:%d' %(self.name, self.age, self.__phone))

    def get_name(self):
        return self.name

    def set_property(self, nam, ag):
        self.name = nam
        self.age = ag
        self.__set_phone(999999999)

    def __del__(self):
        print("delete human %s" %self.name)

def main():
    hum1 = human("armwind1",29, 66666)
    hum1.print_property()
    hum1.set_property("armwind11", 28)
    hum1.print_property()
    p_name = hum1.get_name()
    print('hum1 name:%s' %p_name)

    del hum1

    hum2 = human("armwind2",30, 88888)
    hum2.print_property()
    hum2.set_property("armwind22", 31)
    hum2.print_property()
    p_name = hum2.get_name()
    print('hum2 name:%s' %p_name)

if __name__ == '__main__':
    main()

输出结果:

D:\test\python>python class.py
create human armwind1
name:armwind1, age:29, phone:66666
name:armwind11, age:28, phone:999999999
hum1 name:armwind11
delete human armwind11
create human armwind2
name:armwind2, age:30, phone:88888
name:armwind22, age:31, phone:999999999
hum2 name:armwind22
delete human armwind22

10.global

Python中定义函数时,若想在函数内部对函数外的变量进行操作,就需要在函数内部声明其为global。

g_name = 'armwind1'

def set_name(name) :
    g_name = name

def main():
    print(g_name)
    set_name("armwind2")
    print(g_name)

if __name__ == '__main__':
    main()

输出结果:

D:\test\python>python gloa.py
armwind1
armwind1

上面能够看到设置了名字竟然没有变化,这是由于name是全局变量,需要在函数内部声明一下name为全局变量。具体声明如下:

g_name = 'armwind1'

def set_name(name) :
    global g_name
    g_name = name

def main():
    print(g_name)
    set_name("armwind2")
    print(g_name)

if __name__ == '__main__':
    main()

结果:

D:\test\python>python gloa.py
armwind1
armwind2

11.raise

字面意思就是提出,也就是发起一个系统异常,立即终止当前进程,这与windows的signal和类似。但这和try…except捕获异常防止进程停止正好相反

print("hello world")
raise NameError

运行结果:

D:\test\python>python raise.py
hello world
Traceback (most recent call last):
File “raise.py”, line 2, in
raise NameError
NameError

12.if、elif、else

这里面的else除了和if组成我们常见语句还和while,for也是有关系的,不过最常见还是和if搭配.有c语言编程基础的一看即会。

#try else test
def try_else_test():
    try:
        a = int('aa')
    except ValueError as e:
        print("ValueError")
    else:
        print("all ok")

#for else test
def for_else_test():
    c = [1,2]
    for i in c:
        print(i)
    else:
        print("done")

def main():
    count=0
    while count > 12:
        if (11 > 0):
            print("count > 12,break")
            break
        count += 1
    else:
        print('game over')
    try_else_test()
    for_else_test()
    #if test
    num = int(input('please input:'))
    if num > 0:
        print('%d > 0 ' %num)
    elif num == 0:
        print('%d == 0' %num)
    else:
        print('%d < 0' %num)

if __name__ == '__main__':
    main()

运行结果:

game over
ValueError
1
2
done
please input:-1
-1 < 0

13.import、from

这两个都是导入模块和模块内部方法时使用的,其中模块导入一般有中方式

  • 直接使用import xxx,其中xxx就是模块的名字,这个很常见,一把都是这样用的。使用是一般是模块名字加类名或者方法名,如xxx.yyyy(),其中xxx为模块名字,yyy为类名或者方法名字。

  • 使用from单独导入某个类或者方法,这样就不需要在使用时加入模块名字了。具体可以参考下面测试例子

  • 创建hello 模块

class hello1:
    def __init__(self):
        print("I'm hello1")
    def test(self):
        print("hello world1")

class hello2:
    def __init__(self):
        print("I'm hello2")
    def test(self):
        print("hello world2")

class hello3:
    def __init__(self):
        print("I'm hello3")
    def test(self):
        print("hello world3")
  • 导入hell模块
import hello
from hello import hello1

te1 = hello1()
te2 = hello.hello2()
te2.test()
te3 = hello3()

上面测试例程导入了hello模块,同时也使用from导入了模块中的hello1类,那么分别使用hello1类名和hello.hello2()方法调用了相应的方法。但是没有直接导入hello3方法,也没有在使用时使用模块名字使用类,这样就直接报错了,下面可以看到hello3不能直接使用。

运行结果:

D:\test\python>python test.py
I’m hello1
I’m hello2
hello world2
Traceback (most recent call last):
File “test.py”, line 7, in
te3 = hello3()
NameError: name ‘hello3’ is not defined

14.while

此关键字同c语言中的while具有同样的性质,后面可以接bool值或表达式,格式不同罢了。

c = 0
while (c < 5) :
    c = c+1
    print("c:%d" %c)

运行结果:

D:\test\python>python while.py
c:1
c:2
c:3
c:4
c:5

15.with、as

  • with内置函数可以让python解释器自动关闭文件流,开发人员不用关心文件是否已经被关闭。
  • as:字面意思就是当做的意思,可以把对象重新命名。
dat=['armwind1','armwind2']
try :
    print  dat[3]
except IndexError as e:
    print('IndexError:%s' %e)
finally :
    print("do something")

with open('data.txt','w+') as file:
    file.write('hello world')
    print("write success")
    file.seek(0,0)
    print(file.read())

运行结果如预期一样,只是不要忘记移动文件指针。

D:\test\python>python as.py
IndexError:list index out of range
do something
write success
hello world

16.lambda

xy = lambda x, y: x - y冒号前是参数,冒号后是表达式输出.使用lambda时,不需要重新定义函数,就可以实现一个类似于函数的变量。即简化代码又提高代码运行速度。

def test(p1,p2):
    return lambda x : p1*x + p2*x

def main():
    add = lambda x, y : x+y
    print("add:%d" %add(1,2))

    lam = test(1,2)
    print('lam(2):%d' %lam(2))

if __name__ == '__main__':
    main()

执行结果:

D:\test\python>python lamda.py
add:3
lam(2):6

17.yield

用的不多请参考 https://blog.youkuaiyun.com/mieleizhi0522/article/details/82142856

<think>我们正在使用IPython,这是一个增强的Python交互式环境。在IPython中,我们可以方便地查看Python关键字内置函数(预定义标识符)。 根据引用[1][2][3],我们知道可以使用keyword模块来查看Python关键字。另外,我们可以查看内置函数的名字(注意:内置函数不是关键字,但也是预定义的标识符)。 步骤: 1. 导入keyword模块,使用keyword.kwlist查看所有关键字。 2. 查看内置函数:可以通过内置模块builtins(在Python 3中)来查看,但通常我们也可以直接查看__builtins__模块(在交互式环境中)的字典,或者使用dir(__builtins__)查看所有内置函数属性。 3. 在IPython中,我们还可以使用一些魔法命令,例如使用“?”来获取帮助,但这里我们主要使用Python代码。 注意:关键字是语言保留的,不能用作标识符;而内置函数的名字虽然可以被覆盖,但通常也不建议覆盖。 具体操作: 查看关键字: import keyword keyword.kwlist 查看内置函数内置异常等(注意:dir(__builtins__)会返回一个列表,包含内置函数、异常其他属性的名称): 我们可以通过dir(__builtins__)然后过滤出可调用的对象(函数)或者通过观察名字(通常小写的是函数,但也有一些异常对象)来查看。 但是,更准确的方式是:使用内置模块builtins(需要导入,但在__builtins__中已经存在)。 在IPython中,我们可以这样做: import builtins # 然后获取所有内置函数的名称 [name for name in dir(builtins) if callable(getattr(builtins, name))] 但是,由于内置模块中还有一些类(例如int, str)以及异常等,所以上述方法会返回非常多。我们也可以只关注那些不是类且不是异常的可调用对象?但这样区分比较麻烦。 实际上,我们通常直接查看dir(builtins)输出,然后人为区分。 另外,引用[3]中提到了在命令行交互环境中查看关键字的方法,我们可以在IPython中同样使用。 因此,我们编写以下代码: 1. 查看关键字: import keyword print("Python关键字:", keyword.kwlist) 2. 查看内置函数(预定义标识符): 我们可以使用dir(__builtins__)来查看,但为了更清晰,我们可以打印出所有内置函数(可调用对象)的名字。 注意:在IPython中,我们还可以使用“?”来获取帮助,例如输入“keyword?”可以查看keyword模块的帮助。 下面给出IPython中的操作步骤: 步骤一:查看关键字 In [1]: import keyword In [2]: keyword.kwlist 步骤二:查看内置函数 我们可以先查看__builtins__模块中的内容: In [3]: dir(__builtins__) 但是输出会很长,我们可以使用列表推导式来过滤出函数(可调用对象): In [4]: [f for f in dir(__builtins__) if callable(getattr(__builtins__, f))] 但是注意,这样可能会包含一些类(因为类也是可调用的)。如果我们只想看函数,可以进一步用类型判断,但这样更复杂,而且内置函数中有些是类(如int, str),有些是函数(如len, print)。通常我们不需要严格区分。 另外,IPython提供了一个更简洁的内置函数查看方式:使用%魔术命令,但标准方法还是通过dir。 考虑到用户要求,我们直接使用上述方法。 下面给出一个完整的IPython会话示例: ```python In [1]: import keyword In [2]: keyword.kwlist Out[2]: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] In [3]: # 查看内置函数内置类型等(预定义标识符) In [4]: # 使用dir(__builtins__)会输出很长,我们可以分页显示或者只输出函数名字 In [5]: # 我们可以过滤出可调用的对象(包括函数类) In [6]: builtin_callables = [name for name in dir(__builtins__) if callable(getattr(__builtins__, name))] In [7]: # 打印前20个 builtin_callables[:20] Out[7]: ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError'] # 注意:这里输出的是可调用的内置对象,包括异常类、内置函数内置类型等。 ``` 因此,我们可以告诉用户,在IPython中查看关键字内置函数(预定义标识符)的方法。 注意:由于内置函数类的数量很多,我们通常不会全部记住,而是根据需要使用。 另外,在IPython中,我们还可以使用Tab键自动补全,例如输入“__builtins__.”后按Tab,就会列出所有属性。 为了提高可读性,我们可以将内置函数(而不包括异常类)单独列出来,但Python并没有提供这样的内置列表。我们可以参考官方文档,或者使用inspect模块来进一步判断,但这超出了本问题的范围。 总结回答: 在IPython中查看关键字预定义标识符的方法如下: 1. 关键字使用`keyword.kwlist` 2. 预定义标识符(包括内置函数、内置类型等):使用`dir(__builtins__)`,或者进一步过滤可调用对象。 但是,需要注意的是,预定义标识符不仅包括内置函数,还包括内置类型、内置常量(如True, False, None)内置异常等。 另外,引用[1][2][3]中提到的关键字查看方法也适用于IPython。 根据引用[5],我们还可以在IPython使用格式化输出,但这里不涉及。 因此,我们给出以下代码示例: ```python # 在IPython中查看关键字 import keyword print("Python关键字列表:") print(keyword.kwlist) # 查看内置函数等预定义标识符 print("\n内置函数类型等预定义标识符:") # 我们打印前50个以避免过多输出 builtin_names = dir(__builtins__) print(builtin_names[:50]) # 实际使用时可能不需要打印全部 # 如果想只查看函数(不包括类),可以使用inspect模块进行判断,但这里不展开。 ``` 注意:在IPython中,我们可以直接运行这些代码。 相关问题: 1. 如何判断一个字符串是否是Python关键字? 2. 如何在Python中覆盖内置函数?这样做有什么风险? 3. 如何查看Python中所有保留的关键字内置函数? 4. 在IPython中,有哪些快捷方式可以查看帮助? 5. Python中的关键字内置函数有什么区别? 注意:用户的问题是关于IPython的,所以我们在回答中要体现IPython环境。 </think>在 IPython使用以下方法查看 Python 关键字预定义标识符: ### 1. 查看 Python 关键字 使用 `keyword` 模块查看 Python 保留的关键字: ```python In [1]: import keyword In [2]: keyword.kwlist # 列出所有关键字 Out[2]: ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] In [3]: keyword.iskeyword('if') # 检查特定词是否为关键字 Out[3]: True ``` ### 2. 查看内置函数对象(预定义标识符) 使用内置函数 `dir()` 查看当前命名空间中的标识符: ```python In [4]: dir(__builtins__) # 查看所有内置函数对象 Out[4]: ['ArithmeticError', 'AssertionError', ..., 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', # 预定义的复数类型 'copyright', 'credits', ..., 'str', # 预定义的字符串类型 'sum', 'super', 'tuple', 'type', 'vars', 'zip'] ``` ### 3. 使用 IPython 特有功能 IPython 提供增强的交互功能: ```python In [5]: len? # 查看函数文档 Signature: len(obj, /) Docstring: Return the number of items in a container. Type: builtin_function_or_method In [6]: str.*find*? # 使用通配符查找标识符 str.find str.rfind ``` ### 关键区别说明 | 概念 | 关键字 | 预定义标识符 | |----------------|--------------------------------|--------------------------| | **性质** | 语言保留字,不可重新定义 | 内置函数/类,可被覆盖 | | **数量** | 35个(Python 3.9) | 150+个 | | **验证方法** | `keyword.iskeyword()` | `dir(__builtins__)` | | **示例** | `if`, `for`, `def` | `print()`, `str`, `list` | | **是否可变** | 不可修改 | 可重新绑定 | ### 注意事项 1. 关键字不能作为变量名,否则会引发 `SyntaxError` 2. 内置函数可以被覆盖(但不推荐): ```python In [7]: str = 123 # 覆盖内置str类型(危险操作) In [8]: type(str) Out[8]: int # 原str功能已丢失 ``` 3. 恢复覆盖的内置函数:重启 IPython使用 `del str`[^4]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值