1. 程式人生 > >python while循環和雙層循環

python while循環和雙層循環

數字 單個 pre ont 循環輸出 tin con 循環結構 處理

#python中,while語句用於循環執行程序,即在某個條件下,循環執行某段程序,以處理需要重復處理的相同任務。
#while是“當型”循環結構。
i=1
while i<=20:
print(i,end=" ")
i+=1

sum=0
i=1
while i<=100:
sum+=i
i+=1
else:
print("\n",sum)

print("0+2+...+100=",sum)
#從控制臺錄入一個數字,求從1到數字的階乘;
result=1;i=1;numA=0;
numA=int(input("請輸入一個數字:"))
while i<=numA:

result*=i
i+=1
else:
print("循環結束!")
print("結果是:",result)
#使用while循環輸出100以內的素數
x=2
while x<100:
n=2
while n<x-1:
if x%n==0:
break
n+=1
else:
print(x,end=" ")
x+=1
else:
print("循環結束")
#輸出100之內能被7整除的數
nNum=7;lineCount=0;
while nNum<=100:
if nNum%7 !=0:
nNum+=1;
continue
else:
print(nNum,end=" ")

lineCount+=1
if lineCount==5:
    print()  #單個print()換行;
    lineCount=0
nNum+=1;

else:
print("\n循環結束")
#使用while循環計算從1到100之和
sum=0;i=1;
while i<=100:
sum+=i;
i+=1;
else:
print("1+2+3+...+100=",sum);
print("\n程序結束")
#從控制臺錄入打印符號的數量。
row=0;i=0;
row=int(input("請輸入行數:"));
while i<row:

print()
print("
",end=" ")
i+=1;
else:
print("\n程序運行結束")
#使用while循環和for循環嵌套.python語言允許在一個循環體中嵌套另外一個循環體。
#實例:從控制臺輸入行數和列數,打印正方形。
i=1;j=1;
numA=int(input("請輸入行數:"))
numB=int(input("請輸入列數:"))
while i<=numA:
j=1
while j<=numB:
print("*",end=" ")
j+=1
print()
i+=1

#使用while循環嵌套打印九九乘法口訣表;
i=1;j=1;
while i<=9:
j=1
while j<=i:
print("%d%d=%2d"%(j,i,ij),end=" ")
j+=1
print()
i+=1
else:
print("\n程序運行結束")

#使用for循環打印九九乘法口訣表;
for i in range(1,10):
for j in range(1,10):
if j<=i:
print("%d%d=%2d"%(j,i,ij),end=" ")
else:
print()
else:
print("\n程序運行結束");

python while循環和雙層循環