python基礎之if,while,for使用方法

2021-10-18 21:30:31 字數 2013 閱讀 4146

條件選擇結構格式

if…else

a=

30if a>

100and a<

150:

#注意冒號

print

("你好"

)else

:#注意冒號

print

("hello world"

)#輸出hello world

if …elif…else

a=

30if a>

50and a<

150:

print

("你好"

)elif a>

150:

print

("他好"

)else

:print

()

if巢狀

a=

30if a>

50and a<

150:

print

("你好"

)if a>

50and a<

100:

print

("我好"

)elif a>

100and a<

120:

print

("她好"

)else

:print()

elif a>

150:

print

("他好"

)else

:print

()

while迴圈與else使用

i=

0while i<=10:

#判斷執行條件,注意冒號

print

(i) i=i+

1else

:#while條件不滿足是退出迴圈,執行下面語句

print

(i)#輸出0到11

while迴圈之continue和break使用

i=

1sum=0

while i<=20:

print

(i)if i==10:

print

("第10次迴圈"

) i=i+

1continue

#結束本次迴圈,開始下一次迴圈 或break跳出這個迴圈

j=1while j<=12:

sum=

sum+

1print

(i,j)

j=j+

1 i=i+

1

for迴圈

for i in

range(1

,15,4

):print

(i);

#range(1,15,4)的意思是從1到14,4個數字取乙個,及陣列為1,5,9,13

for迴圈對列表,元組操作

list1=[1

,2,3

,4,5

]tuple1=(5

,6,7

,8,9

)for i in list1:

#對陣列進行遍歷

print

(i)#輸出1,2,3,4,5

for j in tuple1:

#對元組進行遍歷

print

(j)#輸出5,6,7,8,9

for迴圈對字典和集合操作

dict1=

jihe1=

for i in dict1:

#遍歷字典

print

(i)#輸出name,age

print

(dict1[i]

)#輸出張三,18

for i in jihe1:

#遍歷集合

print

(i)#輸出a,b,c

python基礎之語句 Python基礎之條件語句

我們在程式設計中經常需要通過檢查某個條件,從而決定去做什麼。條件語句就是針對這一情景應用的。本篇主要介紹 if 和 while。一 if語句 先來個總覽 if 條件一 條件一對應的 塊 elif 條件二 條件一對應的 塊 else 不滿足條件一和條件二對應的 塊 if 語句的核心就是值為true 或...

Python程式設計基礎之Python基礎

1.只能是乙個詞 2.包含字母,數字和下劃線 3.不能以數字開頭 this program syas hello and asks for your name print hello world1 print what is your name?ask for their name myname i...

python基礎之python介紹

一 python介紹 python的主要應用領域 哪些公司正在應用 cia 美國中情局 就是用python開發的 nasa 美國航天局 nasa 大量使用python進行資料分析和運算 facebook 大量的基礎庫均通過python實現的 redhat 世界上最流行的linux發行版本中的yum包...