条件语句
if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
elif 判断条件3:
执行语句3……
else:
执行语句4……
num = 9
if num >= 0 and num <= 10: # 判断值是否在0~10之间
print (num,'在0~10之间')
循环语句
while循环
while 判断条件(condition):
执行语句(statements)……
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("结束了")
while … else 在循环条件为 false 时执行 else 语句块:
a= 0
while a< 5:
print(a, " is less than 5")
a = a + 1
else:
print(a, " is not less than 5")
for循环
遍历任何序列的项目,如一个列表或者一个字符串。
for iterating_var in sequence:
statements(s)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('当前水果: %s'% fruit)
for ...else在循环正常执行完后执行
嵌套循环
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
while expression:
while expression:
statement(s)
statement(s)
i = 2
while(i < 20):
j = 2
while(j <= (i/j)):
if not(i%j): break
j = j + 1
if (j > i/j) : print(i, " 是素数")
i = i + 1
print ("Good bye!")
break
break终止循环,跳出整个循环
for letter in 'Python':
if letter == 'h':
break
print ('当前字母 :', letter)
continue
跳出本次循环
for letter in 'Python':
if letter == 'h':
continue
print ('当前字母 :', letter)