Python基本語法 迴圈語句

2021-09-10 06:49:49 字數 1905 閱讀 4311

學習筆記以備日後溫習:《python3入門與高階》

分支迴圈條件與列舉

包、模組、函式

功能:輸入賬號密碼完成開鎖

account = 'qiyue'

password = '123456'

print('please input account')

user_account = input()

print('please input password')

user_password = input()

if account==user_account and password==user_password:

# '''問題一:=是賦值,==表示判斷是否相等'''

# '''問題二:兩個表示式邏輯關係是且,因此用and'''

print('success')

else:

# '''問題三:else後面有冒號:'''

print('fail')

pass  #空語句/佔位語句
迴圈語句

#迴圈中while一般在遞迴中常用

counter = 1

while counter <=10:

counter +=1

print(counter)

else:

print('終於打到最強王者')

#for主要用來遍歷/迴圈 序列或者集合、字典

for x in a:

for y in x:

print(y) #輸出為一列

print(y,end='') #輸出為一行

由於 python 並不支援 switch 語句,所以多個條件判斷,用 elif 來實現,或者用dict

#dict is better than switch

a = input()

print(fruits[a])

多維度迴圈中,break跳出的是內層迴圈,不影響最外層迴圈

for x in a:

for y in x:

if y=='orange':

print(y)

esle:

print('fruit is gone')

輸出為 12

3fruit is gone

~~~~~~~~~~~~~~~~~~~~分割線~~~~~~~~~~~~~~~~~~~~~~~

for x in a:

if 'banana' in x:

break

for y in x:

if y=='orange':

print(y)

else:

print('fruit is gone')

無輸出!!因為break跳出了最外層的if else迴圈,不在列印fruit is gone

列印10個數字

#c++中

for(i=0;i<10;i++)

#python中

for x in range(0,10):

print(x)

for x in range(0,10,2):

print(x,end='|')

#0|2|4|6|8|

列印奇數

a=[1,2,3,4,5,6,7,8]

for x in range(0,len(a),2): #range(起始位,末尾位,步長)

print(a[x],end='|') #1|3|5|7|

python基本迴圈語句

if else迴圈語句 if 判斷條件 執行語句 if 判斷條件 執行語句 elif 判斷條件 執行語句 else pass 三目運算 result1 if 判斷條件 else result2 while迴圈語句 while 判斷條件 執行語句 while 判斷條件 執行語句 else 執行語句 w...

迴圈語句的語法

switch選擇結構概述 語法 switch 表示式 先計算表示式的值,再逐個和case 後的常量表示式比較,若不等則繼續往下比較,若一直不等,則執行default後的語句 若等於某乙個常量表示式,則從這個表示式後的語句開始執行,並執行後面所有case後的語句。與if語句的不同 if語句中若判斷為真...

Python全棧04 基本語法 迴圈

迴圈這裡和c語言基本相同,直接做例子吧。列印空心矩形 length input 請輸入矩形的長 width input 請輸入矩形的寬 length int length width int width for i in range width if i 0 or i width 1 for j i...