Python條件語句與迴圈

2021-09-21 03:31:14 字數 2140 閱讀 7272

1、判斷與迴圈

python 縮排

main:

print("hello")

print("hello world.")

if 判斷條件:

執行語句

elif 判斷條件:

執行語句

else:

執行語句

while 判斷條件:

執行語句

a = 100

while a>1:

print(a)

a-=1

if a==50:

break

# 退出迴圈

if a==55:

print("5555555555")

continue

# 此次迴圈結束,進入下乙個迴圈

break 跳出迴圈

continue 進入下一次迴圈

for item in sequence:

執行語句

l = ["a","b","c","d","e","f"]

print(l[:])

print(l[0:5]) # 大於等於0 小於5 0 <= a > 5

print(l[0:-1]) # 大於等於0 小於5 0 <= a > 5

for x,y in enumerate(l): # 列印列表中元素以及下標

print(x,y)

2、程式設計思想最重要

程式語言最重要的是思想

abcd乘以9=dcba,求a=?,b=?,c=?,d=?

for a in range(1,10):

for b in range(0,10):

for c in range(0,10):

for d in range(1,10):

start = 1000*a+100*b+10*c+d

end = 1000*d+100*c+10*b+a

if start * 9 == end:

print("a={}".format(a))

print("b={}".format(b))

print("c={}".format(c))

print("d={}".format(d))

print(" * 9 = ".format(start,end))

返回結果:

a=1b=0

c=8d=9

1089 * 9 = 9801

3、求階乘

求1-n的階乘的和

1!+ 2!+ 3!+ 4!+5 !+ ··· + n!

0! = 1

1!= 1

2!= 1 2 = 2

3!= 1 2 * 3 = 6

def

one(n):

total = 1

if n ==0:

total = 1

else:

for i in range(1,n+1):

total *= i

return total

print(one(3))

status=1

while status:

result = 0

n= input("please input a number(n>=0) : ")

for i in n:

ifnot i.isdigit():

print("the number of you input is error.")

exit(1)

if int(n) < 0:

print("the number of you input is error.")

break

for i in range(0,int(n)+1):

result += one(i)

print("0! + 1! + 2! + ··· ··· + n! = {}".format(result))

python條件語句與迴圈語句

1.if語句 if 語句用於控制程式的執行,基本形式為 if 判斷條件1 執行語句 elif 判斷條件2 執行語句 else 執行語句判斷條件成立時,則執行後面的語句。執行內容可以多行,以縮進來區分表示同一範圍。else 為可選語句,判斷條件不成立時則可以執行相關語句。score 89if scor...

python的條件語句與迴圈語句

else後面要加 elif語句即為else if,用來檢查多個表示式是否為真,並在為真時執行特定 塊中的 list.pop 0 刪除指定位置的元素 list.remove val 刪除指定數值的元素 只有為true才能讓程式正常執行 while true 無限迴圈 while count 可以用來限...

python 條件控制與迴圈語句

本學期學習機器學習,今天來重新看了一下python的語法。和其他語言中的語法一樣,if else 語言。例子 如下 x int input please enter first value1 y int input please enter second value2 z int input ple...