万字干货,Python语法大合集,一篇文章带你入门( 六 )


""""range(lower, upper, step)" returns an iterable of numbersfrom the lower number to the upper number, while incrementingby step. If step is not indicated, the default value is 1.prints:46"""for i in range(4, 8, 2):print(i)复制代码如果使用enumerate函数,可以同时迭代一个list的下标和元素:
"""To loop over a list, and retrieve both the index and the value of each item in the listprints:0 dog1 cat2 mouse"""animals = ["dog", "cat", "mouse"]for i, value in enumerate(animals):print(i, value)复制代码while循环和C++类似,当条件为True时执行,为false时退出 。并且判断条件不需要加上括号:
"""While loops go until a condition is no longer met.prints:0123"""x = 0while x < 4:print(x)x += 1# Shorthand for x = x + 1复制代码捕获异常Python当中使用try和except捕获异常,我们可以在except后面限制异常的类型 。如果有多个类型可以写多个except,还可以使用else语句表示其他所有的类型 。finally语句内的语法无论是否会触发异常都必定执行:
# Handle exceptions with a try/except blocktry:# Use "raise" to raise an errorraise IndexError("This is an index error")except IndexError as e:pass# Pass is just a no-op. Usually you would do recovery here.except (TypeError, NameError):pass# Multiple exceptions can be handled together, if required.else:# Optional clause to the try/except block. Must follow all except blocksprint("All good!")# Runs only if the code in try raises no exceptionsfinally:#Execute under all circumstancesprint("We can clean up resources here")with操作在Python当中我们经常会使用资源,最常见的就是open打开一个文件 。我们打开了文件句柄就一定要关闭,但是如果我们手动来编码,经常会忘记执行close操作 。并且如果文件异常,还会触发异常 。这个时候我们可以使用with语句来代替这部分处理,使用with会自动在with块执行结束或者是触发异常时关闭打开的资源 。
以下是with的几种用法和功能:
# Instead of try/finally to cleanup resources you can use a with statement# 代替使用try/finally语句来关闭资源with open("myfile.txt") as f:for line in f:print(line)# Writing to a file# 使用with写入文件contents = {"aa": 12, "bb": 21}with open("myfile1.txt", "w+") as file:file.write(str(contents))# writes a string to a filewith open("myfile2.txt", "w+") as file:file.write(json.dumps(contents)) # writes an object to a file# Reading from a file# 使用with读取文件with open('myfile1.txt', "r+") as file:contents = file.read()# reads a string from a fileprint(contents)# print: {"aa": 12, "bb": 21}with open('myfile2.txt', "r+") as file:contents = json.load(file)# reads a json object from a fileprint(contents)# print: {"aa": 12, "bb": 21}可迭代对象凡是可以使用in语句来迭代的对象都叫做可迭代对象,它和迭代器不是一个含义 。这里只有可迭代对象的介绍,想要了解迭代器的具体内容,请移步传送门:
Python——五分钟带你弄懂迭代器与生成器,夯实代码能力
当我们调用dict当中的keys方法的时候,返回的结果就是一个可迭代对象 。
# Python offers a fundamental abstraction called the Iterable.# An iterable is an object that can be treated as a sequence.# The object returned by the range function, is an iterable.filled_dict = {"one": 1, "two": 2, "three": 3}our_iterable = filled_dict.keys()print(our_iterable)# => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface.# We can loop over it.for i in our_iterable:print(i)# Prints one, two, three复制代码我们不能使用下标来访问可迭代对象,但我们可以用iter将它转化成迭代器,使用next关键字来获取下一个元素 。也可以将它转化成list类型,变成一个list 。
# However we cannot address elements by index.our_iterable[1]# Raises a TypeError# An iterable is an object that knows how to create an iterator.our_iterator = iter(our_iterable)# Our iterator is an object that can remember the state as we traverse through it.# We get the next object with "next()".next(our_iterator)# => "one"# It maintains state as we iterate.next(our_iterator)# => "two"next(our_iterator)# => "three"# After the iterator has returned all of its data, it raises a StopIteration exceptionnext(our_iterator)# Raises StopIteration# We can also loop over it, in fact, "for" does this implicitly!our_iterator = iter(our_iterable)for i in our_iterator:print(i)# Prints one, two, three# You can grab all the elements of an iterable or iterator by calling list() on it.list(our_iterable)# => Returns ["one", "two", "three"]list(our_iterator)# => Returns [] because state is saved


推荐阅读