一、條件控制
一條或多條語句的執行結果(True/False)來決定執行的代碼塊。
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
- 每個條件後面要使用冒号
,表示接下來是滿足條件後要執行的語句塊。:
- 使用
來劃分語句塊,相同縮進數的語句在一起組成一個語句塊。縮進
- 在Python中
。沒有switch – case語句
# 判斷1-7 奇偶數
a =1;
while a<7 :
if(a %2 == 0) :
print(a,'is even')
else:
print(a,'is odd')
a+=1
- if語句的判斷條件是根據表達式的
來進行判斷的,在python中表示False的資料點選False種類True/False
# True/False
var1 =1
var2 = 0
if var1 :
print(True,'var1')
else:
print(False)
if var2:
print('var2True')
else:
print('var2False')
#True var1
#var2False
- 多個
進行操作。if elif else
# 多個if elif else
age = int(input('print your dog age:'))
if age<=0:
print('Are you hanhan?')
elif age==1:
print("dog age 14")
elif age==2:
print("dog age 22")
elif age>2:
dog_age = 22+(age-2)*5
print(dog_age)
input("exit")
- if中常用的操作運算符
,具體可以翻看之前寫的文章得知用法。< <= > >= == !=
- if嵌套,if中嵌套多個内容,當if語句中的
條件語句重複,以第一個條件為準
- if語句中條件過長,可以使用
來換行。\
-
在同一個縮進下,表示同一個代碼塊,不可以使用{}将代碼括号起來。這樣會表示為一個集合,當有多個語句的時候,還會報錯。
age= 2
if age<=0:
print('Are you hanhan?')
elif age==1:
print("dog age 14")
elif age==2:
print('repeat') #repeat
elif age==2:
print("dog age 22")
elif age==2:
dog_age = 22+(age-2)*5
print(dog_age)
num=int(input("輸入一個數字:"))
if num%2==0:
if num%3==0:
print ("你輸入的數字可以整除 2 和 3")
else:
print ("你輸入的數字可以整除 2,但不能整除 3")
else:
if num%3==0:
print ("你輸入的數字可以整除 3,但不能整除 2")
else:
print ("你輸入的數字不能整除 2 和 3")
#if (name == "pag"):{
# print(name == "pag")
#print("line 2 of if condition")
#}
# File "test.py", line 4
# print("line 2 of if condition")
#^
#SyntaxError: invalid syntax
- 例子:x取0-99,y取0-199,x=y結束,并計算一共輸出幾次。
# x = 0-99 y=0-199 x>y =x x=y =x+y x<y =y
#當x=y 的次數,并且停止
import random
a = 0
while(True):
x =random.choice(range(100))
y =random.choice(range(200))
print(x,y)
a+=1
if x>y:
print(x)
elif x==y:
print('x=y,and a=',a)
break
else:
print(y)
二、語句循環
(1)while
- python中循環
和for
,沒有while
語句do..while / switch..case
- 同樣使用
。冒号和縮進
- 當條件一直滿足的時候,會進入無線循環
- 如果條件隻有一條語句,那麼就可以将語句與while寫在一行上。
while 判斷條件(condition):
執行語句(statements)……
- 1-100的總和
# 計算1-100的綜合
a =1
sum=0
while a<=100:
sum+=a
a+=1
print(sum) #5050
-
語句,當while條件為while使用else
的時候執行else語句塊。false
while <expr>:
<statement(s)>
else:
<additional_statement(s)>
#while else
a=0
while a :
print(True)
else:
print(False)
#False
(2)for循環
- for循環可以周遊任何序列的項目,如一個清單、字元串,周遊
的資料都可以循環。可疊代
- 可以搭配else使用,不滿足的時候,使用else後的語句。
for <variable> in <sequence>:
<statements>
else:
<statements>
# for
x1=[1,2,3,4,5]
x2=('a','b','c')
x3 ={'one','tow','three'}
x4={'hello':'world','hi':'yesyinnng'}
x5 =set('qwer')
for x11 in x1:
print(x11) #1 2 3 4 5
for x22 in x2:
print(x22) #abc
for x33 in x3:
print(x33)#one tow three
for x44 in x4:
print(x44)#hello hi # key
for x55 in x5:
print(x55) #qwer
for x41 in x4.values(),x4.keys():
print(x41) # world hello
#x4={'hello':'world','hi':'yesyinnng'}
# x41先周遊 所有的alues 再周遊所有的keys
#for a,b in x4.values():
# print(a)
# 需要解析的詞太多
for a,b in x4.keys(),x4.values():
print(a) #hello world -- a對因的key alue
- dict 使用for進行周遊,
,轉換出來最好是str類型。keys()對鍵進行周遊,values()對值進行周遊,items()對key,value都有效,如果直接寫變量名,則是輸出key,
-
a會先周遊x輸出後,再周遊y。注意x,y的内容。并且注意a輸出的形式。for a in x,y
# for--dict
dict1 = {1:"one",2:"two",3:"three"}
print(dict1.keys()) #dict_keys([1, 2, 3])
print(dict1.values())#dict_values(['one', 'two', 'three'])
for k1 in dict1.keys():
print(k1) #1,2,3
for v1 in dict1.values():
print(v1) # one two three
for a in dict1.keys(),dict1.values():
print(a,'1') # a 周遊key之後再周遊alues
#dict_keys([1, 2, 3]) 1
#dict_values(['one', 'two', 'three']) 1
#for a1,b1 in dict1.keys(),dict1.values():
#dict 隻周遊key ValueError: too many values to unpack (expected 2)
for a1 in dict1:
print(a1)# 123
#for a2,b2 in dict1:
# print(a)
#TypeError: 'int' object is not iterable
for a2 in dict1.items():
print(a2) # items 輸出為元祖的形式
#(1, 'one')
#(2, 'two')
#(3, 'three')
for a3,b3 in dict1.items():
print(a3,b3)
#1 one
#2 two
#3 three
-
:跳出目前循環體,不再進行下一次循環break
- 如果需要周遊數字序列,可以使用内置
函數,會生成數列。具體後期補range的具體用法。range()
-
擷取指定區間的值,range(x,y)
的取值方法。左開右閉
-
以一定的增量來擷取值,和切片功能相似,step可正、可負range(x,y,step)
- range也可以用來建立一個清單
輸出[0,1,2,3,4],list(range(5)
從0開始
>>>for i in range(5):
... print(i)
...
0
1
2
3
4
>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
>>>
break、continue、else、pass
-
直接跳出所有循環break
-
跳出本次循環,還可以繼續下一次。continue
- 如果在
中使用for、while
,會直接退出,break
語句不執行。else
-
是空語句,為了保持程式結構的完整性,不做任何事情,pass
。占位語句
for letter in 'Runoob':
if letter == 'o':
pass
print ('執行 pass 塊')
print ('目前字母 :', letter)
print ("Good bye!")
- 如果 else 語句和 while 循環語句一起使用,則
當條件變為 False 時,則執行 else 語句。
- 如果 else 語句和 for 循環語句一起使用,
是以else一定會執行。但是while的else隻有在false的時候會執行。else 語句塊隻在 for 循環正常終止時執行!
-
是為了防止文法錯誤,如果沒有内容,那麼就先用pass代替一下。pass