1. 程式人生 > >python 基礎 2.1 if 流程控制(一)

python 基礎 2.1 if 流程控制(一)

字符串 ace 冒號 rip inpu root 類型 真的 use

一.if else 1.if 語句 if expression: //註意if後有冒號,必須有 statement(s) //相對於if縮進4個空格 註:python使用縮進作為其語句分組的方法,建議使用4個空格 2.示例: 1》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python #coding=utf-8 if 1: //在python中1為真(true),0為假(fluse) print "hello python" //當為真的時候輸出“hello python” else: print "hello linux" //否則就輸出“hell linux”
運行如下: [root@localhost python-scripts]# python 11.py hello python 2》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python #coding=utf-8 if 0: //只有當條件成立的時候才會執行print "hello python"的語句,否則就執行print "hell linux" print "hello python" else: print "hello linux" 運行如下: [root@localhost python-scripts]# python 11.py
hello linux 3》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python #coding=utf-8 if 1 < 2: //1小於2成立,就會執行下面的語句 print "hello python" else: print "hello linux" 運行結果如下: [root@localhost python-scripts]# python 11.py hello python 4》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python
#coding=utf-8 a = (‘b‘,1,2) if ‘b‘ in a: print "hello python" else: print "hello linux" 運行如下: [root@localhost python-scripts]# python 11.py hello python 5》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python #coding=utf-8 if not 1 > 2: //取反 print "hello python" else: print "hello linux" 運行如下: [root@localhost python-scripts]# python 11.py hello python 6》[root@localhost python-scripts]# cat 11.py #!/usr/bin/python #coding=utf-8 if not 1 > 2 and 1==1: print "hello python" else: print "hello linux" [root@localhost python-scripts]# python 11.py hello python 3.if語句練習:此處用的是input [root@localhost python-scripts]# cat 12.py #!/usr/bin/python #coding=utf-8 sorce = input("please input a num: ") if sorce >= 90: print "A" print "very good" elif sorce >=80: print ‘B‘ print ‘good‘ elif sorce >=70: print ‘pass‘ else: print ‘not pass‘ 4.int 用法 In [1]: int(‘30‘) //30加引號是字符串,通過int又變成數字了 Out[1]: 30 In [2]: type(int(‘50‘)) Out[2]: int //類型為整形 5.if練習,此處用raw_input [root@localhost python-scripts]# cat 12.py #!/usr/bin/python #coding=utf-8 sorce = int(raw_input("please input a num: ")) //此處用的是raw_input,把加引號的數字變成整形 if sorce >= 90: print "A" print "very good" elif sorce >=80: print ‘B‘ print ‘good‘ elif sorce >=70: print ‘pass‘ else: print ‘not pass‘

python 基礎 2.1 if 流程控制(一)