1. 程式人生 > >第3章 Python 的控制語句

第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 ""