Python-if-elif-else語句

來源:互聯網
上載者:User

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

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.