一、for循環語句:
for循環語法:
for 變量 in range(x):
循環需要執行的代碼
range(stop): 0 ~ stop-1
range(start,stop): start ~ stop-1
range(start,stop,step): start ~ stop-1 step(步長)
# print(range(1,10,2))
#1~100之間的所有偶數求和
sum = 0
for i in range(2,101,2):
sum += i
print(sum)
#輸入一個數字,並求出它的階乘
num = int(input('Num:'))
res = 1
for i in range(1,num+1):
res *= i
print('%d的階乘結果爲: %d' %(num,res))
2.for循環的中斷:
break:跳出整個循環,不會再執行循環後面的內容,但是循環之後的內容依然執行
continue:跳出本次循環,continue後面的代碼不再執行,但是循環依然繼續
exit():結束程序的運行
for i in range(10):
if i == 5:
# continue
# break
exit()
print('hello')
print(i)
print('hello python')
#練習1
有1,2,3,4四個數字
求四個數字能生成多少個互不相同且無重複數字的三位數(不能含有122 133類似)
count = 0
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i != j and j !=k and k != i:
print(i * 100 + j * 10 + k)
count += 1
print('生成%d個無重複數字的三位數' %count)
練習2:
1.輸入用戶名和密碼
2.判斷是否正確(name = 'root', passwd = 'westos')
3.登錄僅有3次及會,超過3次,報錯
for i in range(3):
name = input('用戶名: ')
passwd = input('密碼: ')
if name == 'root' and passwd == 'westos':
print('登錄成功!')
break
else:
print('登錄失敗')
print('您還剩餘%d次機會' %(2-i))
else:
print('失敗超過3次,請稍後再試!')
練習3:
#輸入shell中的命令讓其可以運行,按回車時還顯示命令行提示字符
import os ##使輸入中可以使用shell中的命令
# os.system('ls')
# a = input('[kiosk@foundation0 ~]$ ')
# print(a)
for i in range(1000): ##在後面提到while後可以進入死循環,本處只是個例子
cmd = input('[kiosk@python ~]$ ')
if cmd:
if cmd == 'exit':
print('logout')
else:
os.system(cmd)
else:
continue
練習4:
最小公倍數 = (num1 * num2) / 最大公約數
#1.接收兩個數字
num1 = int(input('Num1: '))
num2 = int(input('Num2: '))
#2.找出兩個數中的最小值
min_num = min(num1,num2)
#3.最大公約數範圍在1~min_num之間
for i in range(1,min_num+1):
if num1 % i ==0 and num2 %i ==0:
gys = i
#4.最小公倍數
gbs = (num1*num2 / gys)
print('%d和%d的最大公約數爲: %d' %(num1,num2,gys))
print('%d和%d的最小公倍數爲: %d' %(num1,num2,gbs))
二、while循環語句:
1.while語句:
while 條件:
條件滿足時,做的事情1
條件滿足時,做的事情2
...
#1.定義計數器
i = 0
#2.開始循環
while i < 3:
#循環內需要做的事情
print('hello python')
#處理計數器
i += 1
while True: ##死循環,只要輸出不爲空就一直循環下去,可以手動終止循環
print('hello python')
練習:求0~100之間的數字和:
i = 0
sum = 0
while i <= 100:
sum += i
i += 1
print('0~100之間的數字求和結果爲: %d' %sum)
2.while嵌套:
練習1:輸出9x9乘法表
row = 1
while row <= 9:
col = 1
while col <= row:
print('%d * %d = %d\t' %(col,row,col*row),end='')
col += 1
print('')
row += 1
練習2:
1.隨機生成1~100的數字
2.5次機會
3.too big
4.too small
5.恭喜,並退出循環
import random
trycount = 0
computer = random.randint(1,100)
print(computer)
while trycount < 5:
# player = int(input('Num: ')) 默認不顯示電腦生成的數字
if player > computer:
print('too big')
trycount += 1
elif player < computer:
print('too small')
trycount += 1
else:
print('恭喜')
break
三、字符串的簡單用法
1.字符串定義方式:
a = 'hello'
b = "westos"
c = 'let\'s go' ##\轉義'
d = "let's go"
e = """ ##"""多行定義
用戶管理系統
1.添加用戶
2.刪除用戶
3.顯示用戶
"""
print(a)
print(b)
print(c)
print(d)
print(e)
print(type(e))
2.字符串的特性
索引:
s = 'hello'
print(s[0])
print(s[1])
切片:
s='hello'
print(s[:3]) #顯示前3位
print(s[0:3])
print(s[0:4:2]) #s[start:end:step] 從start開始,到end-1結束
print(s[:]) #顯示完整字符串
print(s[::-1]) #字符串的反序
print(s[1:]) #顯示第二位到最後一位
print(s[:-1]) #顯示第一位到倒數第二位i
print(s[-1]) #顯示最後一位
重複:
s='hello'
print(s * 5) #把hello連續顯示5次
連接:
s='hello'
print('hello' + 'world')
成員操作符號:
s='hello'
print('h' in s) ##在hello裏面存在這個字符即輸出True,不存在就輸出Flase
print('q' in s)
3.幾個小練習
練習1:迴文數的判斷(設n是一任意自然數。若將n的各位數字反向排列所得自然數n1與n相等,則稱n爲一回文數。)
num = input('Num:')
if num == num[::-1]:
print('迴文數')
else:
print('不是')
練習2:抓取日誌文件的簡單方法,抓取網頁類似
# filename = 'hello.log'
#
# if filename.endswith('.log'):
# print(filename)
# else:
# print('error')
#
url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'http://172.25.254.250/index.html'
if url3.startswith('http://'):
print('爬取網頁')
else:
print('無法爬取')
練習3:判斷變量是否合法
1.第一個字符是否爲字母或者下劃線
2.如果是,繼續
3.如果不是,報錯
4.依次判斷除了第一個字符以外的其他字符
5.判度是否爲字母、數字或者下劃線
while True:
s = input('變量名: ')
if s == 'exit':
print('退出')
break
if s[0].isalpha() or s[0] == '_':
for i in s[1:]:
if not(i.isalnum() or i == '_'):
print('%s變量名不合法' %s)
break
else:
print('%s變量名合法' %s)
else:
print('%s 變量名不合法' %s)
4.字符串的搜索和替換:
s = 'hello world hello'
#find找到子串,並返回最小的索引
print(s.find('hello')) #第一個hello從0開始,所以最小索引爲0
print(s.find('world'))
#rfind找到子串,並返回最大的索引
print(s.rfind('hello')) #最後一個hello從12開始,所以最大索引爲12
#替換
print(s.replace('hello','westos'))
5.字符串的對齊
print('學生管理系統'.center(30)) ##在30個空爲中居中顯示
print('學生管理系統'.center(30,'*')) ##居中顯示並在兩邊加上*
print('學生管理系統'.ljust(30,'*')) ##只在右邊顯示*
print('學生管理系統'.rjust(30,'*')) ##只在左邊顯示*
6.字符串的統計
print('hello'.count('l')) ##hello中有幾個l
print('hello'.count('ll')) ##hello中有幾個ll
print(len('hello')) ##hello中有字符個數
7.字符串的分離和連接
分離:
s = '172.25.254.250'
s1 = s[::-1]
print(s1) ##字符串的倒序
s2 = s.split('.')
print(s2) ##字符串以.爲分隔符拆開
s3 = s2[::-1]
print(s3) ##字符串拆開後倒序
date = '2019-06-23'
date1 = date.split('-')
print(date1)
連接:
print('-'.join(date1))
print('.'.join(s2))
8.字符串的反轉
print(' '.join(input().split()[::-1]))
9.字符串的小練習
練習:給定一個字符串來代表一個學生的出勤紀錄,這個紀錄僅包含以下三個字符:
'A' : Absent,缺勤
'L' : Late,遲到
'P' : Present,到場
如果一個學生的出勤紀錄中不超過一個'A'(缺勤)並且不超過兩個連續的'L'(遲到),那麼這個學生會被獎賞。
你需要根據這個學生的出勤紀錄判斷他是否會被獎賞。
示例 1:
輸入: "PPALLP"
輸出: True
示例 2:
輸入: "PPALLL"
輸出: False
s = input()
if s.count('A') <= 1 and s.count('LLL') == 0:
print(True)
else:
print(False)
四、幾道綜合練習題:
1.(1)隨機生成10以內加(可以是加減乘除)法題目
(2)學生查看題目並輸入答案
(3)判斷學生答案是否正確
(4)退出時,統計答題目總數,並統計正確數量和正確率(保留兩位小數)
import random
fuhao = ['+','-','*','/']
count = 0
right = 0
while True:
a = random.randint(0,10)
b = random.randint(0,10)
c = random.choice(fuhao)
print('%d %s %d = ' %(a,c,b))
question = input('請輸入您的答案:(exit退出)')
if c == '+':
result = a + b
if question == str(result):
print('回答正確')
elif question == 'exit':
break
else:
print('回答錯誤')
count += 1
right += 1
count += 1
elif c == '-':
result = a - b
if question == str(result):
print('回答正確')
elif question == 'exit':
break
else:
print('回答錯誤')
count += 1
right += 1
count += 1
elif c == '*':
result = a * b
if question == str(result):
print('回答正確')
elif question == 'exit':
break
else:
print('回答錯誤')
count += 1
right += 1
count += 1
elif c == '/':
result = a / b
if question == str(result):
print('回答正確')
elif question == 'exit':
break
else:
print('回答錯誤')
count += 1
right += 1
count += 1
if count == 0:
print('錯誤:你還沒有開始答題!!!')
else:
percent = right / count
print('測試結束,共回答%d道題,正確個數爲%d,正確率爲%.2f%%' %(count,right,percent * 100))
2.*的4種打印方法,打印出來應該是下圖所例類型
"""
*
**
***
****
*****
*****
****
***
**
*
*
**
***
****
*****
*****
****
***
**
*
"""
# 定義行變量,從1開始計數
row = 1
# 循環5次
while row <= 5:
print("*" * row) # 第i行打印i個星星
row += 1
# 定義行變量,從1開始計數
row = 5
# 循環5次
while row >= 1:
print("*" * row) # 第i行打印i個星星
row -= 1
#定義行變量,從1開始計數
row = 1
while row <= 5: #打印5行
col = 1 #定義列變量,從1開始計數
while col <= 5: #每行打印5列
if col <= (row - 1):
print(" ", end="")
else:
print("*", end="")
col += 1
print("") #每打印完1行後換行
row += 1
#定義行變量,從1開始計數
row = 1
while row <= 5: #打印5行
col = 5 #定義列變量,從5開始計數
while col >= 1: #每行打印5列,打印row個*,col-row個空格
if col >= (row + 1):
print(" ", end="")
else:
print("*", end="")
col -= 1
print("") #每打印完1行後換行
row += 1