第3章 Python 的控制语句

3.1 结构化程序设计;
3.2 条件判断语句;
3.2.1 if 条件语句;
if (表达式):
语句1
else:
语句2
x = input("x:")
x = int(x)
x = x + 1
print (x)
输入:x:9
10

执行 if 内的程序
a = input("a:")
a = int(a)
b = input("b:")
b = int(b)
if (a > b):
print (a, ">", b)
输出:a:8
b:3
8 > 3
a:2
b:7

if else 语句
a = input("a:")
a = int(a)
b = input("b:")
b = int(b)
if (a > b):
print (a, ">", b)
else:
print (a, "<", b)

3.2.2 if...elif...else 判断语句
score = float(input("score:"))
if 90 <= score <= 100:
print ("A")
elif 80 <= score <= 90:
print ("B")
elif 60 <= score <= 80:
print ("C")
else:
print ("D")

x = -1
y = 99
if (x >= 0):
if (x > 0):
y = 1
else:
y = 0
else:
y = -1
print ("y =", y)

3.2.4 switch 语句的替代方案
使用字典实现switch语句
from __future__ import division
x = 1
y = 2
operator = "*"
result = {"+": x + y, "-": x - y, "*": x * y, "/": x / y}
print (result.get(operator))
输出:2 x*y

class switch(object):
def __init__(self, value):
self.value = value
self.fall = False

def __iter__(self):
yield self.match
raise StopIteration

def match(self, *args):
if self.fall or not args:
return True
elif self.value in args:
self.fall = True
return True
else:
return False

operator = "+"
x = 1
y = 2
for case in switch(operator):
if case("+"):
print (x + y)
break
if case("-"):
print (x - y)
break
if case("*"):
print (x * y)
break
if case("/"):
print (x / y)
break
if case():
print ""
3.3 循环语句 3.3.1 while 循环 numders = input("输入几个数字,用逗号分割:").split(",") print (numders) x = 0 while x < len(numders): print (numders[x]) x += 1 输出:输入几个数字,用逗号分割:123 ['123'] 123 x = float(input("输入x的值:")) i = 0 while(x != 0): if (x > 0): x -= 1 else: x += 1 i = i + 1 print ("第%d次循环:" % (i, x)) else: print ("x等于0:",x) i = 1 while i > 0: i = i + 1 print (i) break 3.3.2 for 循环 for x in range(-1, 2): if x > 0: print ("正数:", x) elif x == 0: print ("零:", x) else: print ("负数:", x) else: print ("循环结束") 输出:负数: -1 零: 0 正数: 1 循环结束 x = 0 while x < 5: print (x) x = x + 2 for x in range(0, 5, 2): print (x) 输出:0 2 4 3.3.3 break 和 continue 语句 operator = "+" x = 1 y = 2 for case in switch(operator): if case("+"): print (x + y) break if case("-"): print (x - y) break if case("*"): print (x * y) break if case("/"): print (x / y) break if case(): print "" x = int(input("输入x的值:")) y = 0 for y in range(0, 100): if x == y: print ("找到数字:", x) break else: print ("没找到") x = 0 for i in [1,2,3,4,5]: if x == i: continue x += i print ("x的值为", x) 3.4 结构化程序实例 def bubbleSort(numbers): for j in range(len(numbers) - 1, -1, -1): for i in range(j): if numbers[i] > numbers[i + 1]: numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i] print (numbers) def main(): numbers = [23, 12, 9, 15, 6] bubbleSort((numbers)) if __name__ == "__main__": main() 输出:[12, 23, 9, 15, 6] [12, 9, 23, 15, 6] [12, 9, 15, 23, 6] [12, 9, 15, 6, 23] [9, 12, 15, 6, 23] [9, 12, 15, 6, 23] [9, 12, 6, 15, 23] [9, 12, 6, 15, 23] [9, 6, 12, 15, 23] [6, 9, 12, 15, 23] 3.6 习题
posted @ 2018-12-21 21:44  无声胜有声  阅读(215)  评论(0)    收藏  举报