python10:条件判断和循环

程序不总是顺序执行的,所以需要条件控制语句来支持分支处理,循环来处理反复多次调用。下面将减少python中的条件判断和循环语法。

条件判断

条件判断就是当某个条件为真时执行某个程序片段,否则执行另一个。

>>> x = int(input("Please enter an integer: "))Please enter an integer: 2>>> if x < 0:x = 0print('Negative changed to zero')elif x == 0:print('Zero')elif x == 1:print('Single')else:print('More')More

循环while

如果你需要在条件满足时反复的做一件事情,则可以使用while语句,下面是Fibonacci序列的例子。

>>> a, b = 0, 1>>> while b < 100:print(b, end = ', ')a, b = b, a+b1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 再看下面的例子,循环直到用户输入不为空的名字,然后打印名字。

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

for

Python中for语句和其它语言中的有些不同,Python中的for语句总是在序列(list或者String)上迭代,按照元素出现在序列中的顺序。例如:

>>> words = ['cat', 'window', 'defenestrate']>>> for w in words:print(w, len(w))cat 3window 6defenestrate 12如果你需要修改你正在迭代的这个序列,你最好在迭代之前复制一个拷贝,使用切片可以很容易的做到。继续使用上面的words:

>>> for w in words[:]:if len(w) > 6:words.insert(0, w)>>> words['defenestrate', 'cat', 'window', 'defenestrate']

range()

如果你需要在一个数字序列上做迭代,则可以使用range(),它用于产生一个数字序列。

>>> for i in range(5):print(i)01234range()产生的序列不包含结束点,range(10)产生10个值,从0开始,9结束。可以为range()指定一个起始点,或者指定一个步长:

>>> list(range(5, 10))[5, 6, 7, 8, 9]>>> list(range(0, 10, 3))[0, 3, 6, 9]>>> list(range(-10, -100, -30))[-10, -40, -70]可以使用range()和len()方便的遍历一个序列:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):print(i, a[i])0 Mary1 had2 a3 little4 lamb需要注意的是,range()给人的感觉是返回一个序列,但实际上它不是。它返回的是一个对象,当你迭代该对象时,该对象将按照你指定的顺序返回你想要的元素,但是它不是一个真正的序列,因此不会占用空间。看下面的输出:

>>> print(range(10))range(0, 10)

break、continue和else

break用于中断最近的那个循环(for或者while)。循环可以有一个else子句,用于当循环完成后或者循环条件为false后执行,但不会在循环遭遇break后执行,看下面的例子:

>>> for n in range(2, 10):for x in range(2, n):if n % x == 0:print(n, 'equals', x, '*', n // x)breakelse:# loop fell through without finding a factorprint(n, 'is a prime number') 2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3上面例子中的else字句对应到内部的for循环,而不是if语句,,当没有break执行时,else子句将被执行。continue字句用于中止这次循环,继续下一次:

>>> for num in range(2, 10):if num % 2 == 0:print("Found an even number", num)continueprint("Found a number", num)Found an even number 2Found a number 3Found an even number 4Found a number 5Found an even number 6Found a number 7Found an even number 8Found a number 9

pass

pass什么也不做,当语法上要求需要一个子句,但你不想进行任何行为时,可以使用。例如:

>>> class MyEmptyClass:pass这里定义了一个空类。也可以定义一个空函数:

>>> def initlog(*args):pass一般在进行测试时可以使用pass。

循环技巧循环获取字典的key和value

对字典进行循环时,使用字典的items()方法,可以同时获取key和value。

>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}>>> for k, v in knights.items():print(k, v)gallahad the purerobin the brave

循环序列同时获取索引和值

使用那个enumerate()函数可以同时获取序列的索引和值:

>>> for i, v in enumerate(['tic', 'tac', 'toe']):print(i, v)0 tic1 tac2 toe

循环多个序列

只用zip()函数可以同时循环多个序列。

>>> questions = ['name', 'quest', 'favorite color']>>> answers = ['lancelot', 'the holy grail', 'blue']>>> for q, a in zip(questions, answers):print('What is your {0}? It is {1}.'.format(q, a))What is your name? It is lancelot.What is your quest? It is the holy grail.What is your favorite color? It is blue.

反向遍历序列

使用reversed()函数可以反向遍历序列。

>>> for i in reversed(range(1, 10, 2)):print(i)97531

遍历排序后的序列

sorted()函数返回一个新的排序后的序列,用于遍历,并且避免源序列被改变。

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']>>> for f in sorted(set(basket)):print(f)applebananaorangepear

循环期间改变序列

如果需要在循环期间改变序列,你需要在循环前先将序列拷贝一份,使用切片可以很容易做到:

到底通向了什么样的远方呢?

python10:条件判断和循环

相关文章:

你感兴趣的文章:

标签云: