第3章 Python 的控制语句,,3.1 结构化程序设


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章 Python 的控制语句

评论关闭