for循環練習1
for i in range(4): print(i)
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py
0
1
2
3
for循環練習2
for x in range(1,40,5): #間隔5
print(x)
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py
1
6
11
16
21
26
31
36
打印99乘法表
for i in range(1, 10): for j in range(i+1): if(j!=0): print('%d*%d=%d\t' % (j, i, i * j), end='') print()
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
for循環數字組合
#不相同數字的數目 num = 0 #對三位數字取值 for g in range(1,5,1): for s in range(1,5,1): for b in range(1, 5, 1): #判斷三個數字是否有相同數字,若沒有則打印且num自加1 if(g != s and g != b and b != s ): print('%d%d%d' %(b,s,g)) num += 1 #輸出有多少個不重復數字 print('共%d個不重復且不相同的數字' %(num))
for循環實現用戶登錄
num=3
for x in range(3):
name = input("姓名:")
pwd = input("密碼:")
if (name == "yuhua") and (pwd == "123"):
print("Login success……")
break
else:
print("賬號密碼錯誤!")
print("還有%d次機會"%(2-x))
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/for循環實現用戶登錄.py
用戶名:yuhua
密碼:123
登陸成功
簡單實現cmd命令
import os
os.system('chcp 65001') #設置cmd窗口為UTF-8
while(True):
cmd = input('[root@python ~]# ')
if cmd:
if cmd == 'exit':
print('logout')
exit(0)
else:
os.system(cmd)
else:
continue
求最大公約數與最小公倍數
a = int(input('輸入第一個數:')) b = int(input('輸入第二個數:')) small = min(a,b) big = max(a,b) sum = 1 for i in range(1,small+1): if (a % i == 0) and (b % i == 0): sum = 1 * i print('最大公約數為:%d' %(sum)) print('最小公倍數為%d' %(a*b/sum)) """" 解法一:∵12=6×2,18=6×3,∴12和18的最小公倍數=6×2×3=36. 解法二:12的倍數由小到大依次為12、24、36、48、60、72…… 18的倍數由小到大依次為18、36、54、72、90…… 因此12和18的最小公倍數為36. D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/求最大公約數與最小公倍數.py 輸入第一個數:12 輸入第二個數:18 最大公約數為:6 最小公倍數為36 """
打印直角三角形
第一種
for row in range(1,6): for col in range(row): print("*",end="") print("")
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py
*
**
***
****
*****
第二種
cols=5 for row in range(1,6): for x in range(cols): print("*",end="") cols-=1 print("")
D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py
*****
****
***
**
*