Source:
#!/bin/env python<br /># coding=gb2312<br /># -*- coding: gb2312 -*-<br />from __future__ import division<br />#### if-else ####<br />print '#### if-else ####'<br />a = input("a: ") # 12 or 10+2<br />b = input("b: ")<br />if(a>b):<br /> print "max: ", a<br />else:<br /> print "max: ", b<br />#### if-elif-else ####<br />print '#### if-elif-else ####'<br />score = raw_input("score: ") # string<br />score = int(score)<br />if(score>=90) and (score<=100):<br /> print "A"<br />elif(score>=80 and score<90):<br /> print "B"<br />elif(score>=60 and score<80):<br /> print "C"<br />else:<br /> print "D"<br />#### switch I ####<br />print '#### switch ####'<br />x = 1<br />y = 2<br />operator = "/"<br />result = {<br /> "+": x+y,<br /> "-": x-y,<br /> "*": x*y,<br /> "/": x/y<br />}<br />print result.get(operator)<br />#### switch II ####<br />print '#### switch II ####'<br />class switch(object):<br /> def __init__(self, value): # init value<br /> self.value = value<br /> self.fall = False # no break, then fall=False<br /> def __iter__(self):<br /> yield self.match # match method to create<br /> raise StopIteration # exception to check loop<br /> def match(self, *args):<br /> if self.fall or not args:<br /> return True<br /> elif self.value in args: # successful<br /> self.fall = True<br /> return True<br /> else: # fail<br /> return False<br />operator = "+"<br />x = 1<br />y = 2<br />for case in switch(operator):<br /> if case('+'):<br /> print x+y<br /> break<br /> if case('-'):<br /> print x-y<br /> break<br /> if case('*'):<br /> print x*y<br /> break<br /> if case('/'):<br /> print x/y<br /> break<br /> if case():<br /> print 'NULL'<br />
Result:
[work@db-testing-com06-vm3.db01.baidu.com python]$ python if_else.py
#### if-else ####
a: 12 + 8
b: 30
max: 30
#### if-elif-else ####
score: 88
B
#### switch ####
0.5
#### switch II ####
3
================================================================
中文注釋參考:
一個極小的問題。在python代碼中,用了中文注釋,不能被python解譯器理解(python 2.5)。解決方案是:
# coding=gb2312
print 'ok' #中文注釋沒問題
或者:
# -*- coding: gb2312 -*-
print 'ok' #這樣也行
代碼詳解參考:
http://blog.csdn.net/Lynn_yan/archive/2010/04/08/5464911.aspx