1. 程式人生 > >Python 基礎入門 4 語句

Python 基礎入門 4 語句

表達 tar 程序 break pin for for in index for循環

"""
判斷語句:if語句,格式如下
if 表達式:
語句1
elif 表達式:
語句
else:
語句

簡單的if語句(當只有一條語句時): if 表達式:語句
"""
if 1<0:
print("哦")
elif 1==0:
print("意義")
else:
print("在")

"""
循環語句:while, 格式如下
while 表達式 當表達式為真時,執行語句1
語句1
else 當表達式為假時,執行語句2(當循環中遇到break時,不執行該語句2)
語句2

簡單的while語句(當只有一條語句時): while 表達式:語句
break語句 退出循環語句,執行下一步程序
continue語句 退出當前循環進入下個循環
"""
num = 1
while num <= 6:
num += 1
if num == 2:
continue
elif num == 6:
break
print(num)
else:
print(num)

"""
循環語句for ,其格式如下
for 變量名 in 集合: (這裏的集合有String,列表,元組等)
語句
邏輯:按索引值順序,從集合中的元素賦值給str,直到集合索引值結束
"""
num = 0;
for str in "string":
print("num = %d" %(num))
num += 1

"""
range([startInt],stopInt,[stepInt]) 創建一個從startInt(包括)開始以stepInt遞增到stopInt(不包括)的列表,startInt默認是0,stepInt默認是1
註意,不能直接用print打印出來,可以用循環語句打印
"""
for str in range(1,5):
print("str = %s" %(str))

"""
enumerate(集合):用於for循環語句,作用是將集合的索引值和元素值返回,註意:dict的元素值返回的是key值
"""
tuple = (1,2,3,"4")
dict = {"key1":"value","key2":"value2"}
for index,str in enumerate(dict):
print(index,str)

Python 基礎入門 4 語句