Python條件語句與循環
阿新 • • 發佈:2018-01-24
orm 編程思想 enc seq 列表 format 返回結果 次循環 else 1、判斷與循環
python 縮進
main:
print("Hello")
print("Hello world.")
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("{0} * 9 = {1}".format(start,end))
返回結果:
A=1
B=0
C=8
D=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:
if not 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條件語句與循環