• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# 循环与分支——python

1周前 (10-18) 8次浏览

python中不支持直到型循环结构(后测循环实现)

``````number = -1
while	number < 0
number = eval(input("Enter a positive number:"))
``````

``````while True:
number = eval(input("Enter  a positive number:"))
if x >= 0 : break;
#若数字有效跳出循环，哨兵循环
print（"The number you entered was not positive"）
``````

<for… else: …> <while… else: …>语句与循环的搭配使用，else:后的表达式在for循环列表遍历完毕后或while 条件语句不满足的情况下执行，

``````# months.py
def main():
for n in range(2,10):
for x in range(2,n):
print("({},{})t".format(n,x))
if n%x == 0:
print(n,'equals',x,'*',n//x)
break;
else:
# loop fell through without finding a factor
print(n,'is a prime number')
main()
``````

2 is a prime number
(3,2)
3 is a prime number
(4,2)
4 equals 2 * 2
(5,2)
(5,3)
(5,4)
5 is a prime number
(6,2)
6 equals 2 * 3
(7,2)
(7,3)
(7,4)
(7,5)
(7,6)
7 is a prime number
(8,2)
8 equals 2 * 4
(9,2)
(9,3)
9 equals 3 * 3

``````if<condition1>:
<case1 statements>
elif <condition2>:
<case2 statements>
……
else:
<default statements>
``````

python的布尔运算符为短路运算符，当前面的表达式已经可以得出该布尔表达式的真假时，布尔表达式便不再进行下去。

x or y中，当x为真，就不在判断y的真假。

``````ans = input("What flavor do you want [vanilla]:")
if ans :
flavor = ans
else:
flavor = "vanilla"
``````

ans = input(“What flavor do you want [vanilla]:”)
flavor = ans or “vanilla”

``````flavor=  input("What flavor do you want [vanilla]:") or "vanilla"
``````

Python解释器遇到一个try语句，它会尝试执行try语句体内的语句

``````try:
<body>
except <ErrorType1>:
<handler1>
except <ErrorType2>:
<handler2>
except <ErrorType3>:
<handler3>
except:
<handler0>
``````