Python學習筆記8 語句

2022-03-05 13:43:35 字數 1926 閱讀 3171

條件語句

有的程式裡寫的是 /usr/bin python,表示 python 直譯器在/usr/bin 裡面。但是,如果寫成 /usr/bin/env,則表示要通過系統搜尋路徑尋找 python 直譯器。不同系統,可

能直譯器的位置不同,所以這種方式能夠讓**更將擁有可移植性。

#

/usr/bin/env python

#coding=utf-8

number = int(raw_input("

請輸入任意乙個整數:"))

if number == 10:

print

"您輸入的數字是: %d

"%number

elif number > 10:

print

"this number is more than 10.

"elif number < 10:

print

"this number is less than 10.

"else

:

print

"are you a human?

"

三元操作符

三元操作,是條件語句中比較簡練的一種賦值方式,它的模樣是這樣的:

>>> a = "5"

if 6>5 else 3

>>>a'5

'>>> a = "5"

if 6<5 else 3

>>>a

3

迴圈語句

for

#

/usr/bin/env python

fruits=["

","orange

","banana"]

for i in

fruits:

print i

多個

a=[(1,2),(3,4),(5,6)]

d=for x,y in

a:print d

while

#!/usr/bin/env python

#coding:utf-8

a = 9

while a:

if a%2 == 0:

break

else:

print "%d is odd number"%a

a = 0

print "%d is even number"%a

while...else

一遇到 else 了,就意味著已經不在 while 迴圈內了。

#

!/usr/bin/env python

count =0

while count < 5:

print count, "

is less than 5

"count = count + 1

else

:print count, "

is not less than 5

"

for...else

這個迴圈也通常用在當跳出迴圈之後要做的事情。

#

!/usr/bin/env python

#coding=utf-8

from math import

sqrt

for n in range(99, 1, -1):

root =sqrt(n)

if root ==int(root):

print

nbreak

else

:print

"nothing.

"

python學習筆記8

主要講了python的輸入和輸出 python通過 python2.x raw input和 python3.x input來實現輸入輸出。input可以加引數,表示為提示符,返回值為你的輸入。比如 age input how old are you?print your age is s age ...

Python學習筆記8(類)

8.1 建立和使用類 class dog def init self,name,age 初始化屬性name和age self.name name self.age age defsit self 模擬小狗被命令石蹲下 print self.name is now sitting def roll s...

Python學習筆記 continue語句

python中continue語句用於跳出本次迴圈,break語句是跳出整個迴圈。continue語句告訴python語言跳出本次迴圈中剩下的語句,執行下一輪迴圈.continue迴圈也用於for迴圈和while迴圈.usr bin python coding utf 8 for letter in...