1. 程式人生 > >Python基礎(linux下)---迴圈語句while,for和字串

Python基礎(linux下)---迴圈語句while,for和字串

for 迴圈的語法:

#for 變數 in range(10):
迴圈需要執行的程式碼
#else:
迴圈結束時需要執行的程式碼

#1+2+3+…+100=
c語言或者java:

sum = 0 
for(int i=1;i<=100;i++):
	sum = sum + i
print sum

python:

sum = 0
for i in range(1,101):
	sum = sum + i
print(sum)

拿出1~10之間的所有偶數

In [6]: range(1,10,2)
Out[6]: [1, 3, 5, 7, 9]
In [7]: range(1,11,2)
Out[7]: [1, 3, 5, 7, 9]

拿出1~10之間的所有偶數

In [8]: range(2,11,2)
Out[8]: [2, 4, 6, 8, 10]

range()函式

range(stop) : 0~stop 1
range(start,stop) : start~stop 1
range(start,stop,step) : start~stop step(步長)

In [1]: range(5)
Out[1]: [0, 1, 2, 3, 4]

In [2]: range(7)
Out[2]: [0, 1, 2, 3, 4, 5, 6]

In [3]: help(range)

In [4]: range(1,10)
Out[4]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

In [5]: help(range)

案例:
使用者登陸程式需求:
1.輸入使用者名稱和密碼
2.判斷使用者名稱和密碼是否正確(name = ‘root’,passwd=‘westos’)
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('登陸機會超過三次,請等待24小時重試!!!!!')

在這裡插入圖片描述

break和continue:

break:跳出整個迴圈,不會再執行迴圈後續的內容
continue:跳出本次迴圈,continue後面的程式碼不再執行,但是還是會繼續迴圈
exit():結束程式的執行

for i in range(10):
	if i == 5:
		break
	print(i)

在這裡插入圖片描述

for i in range(10):
	if i == 5:
		continue
	print(i)

在這裡插入圖片描述

!!!!因為練習題需要先呼叫一些模組,後面模組部分會講到

import os
#死迴圈
while True:
	cmd = input('[[email protected]]$')
	if cmd:
			if cmd == 'exit':
				print('logout')
				break
				print('hello')
			else:
				print('run %s' %(cmd))
				# 執行shell命令
				os.system(cmd)
	else:
		continue
		print('hello')

在這裡插入圖片描述

for語句練習:

輸入兩個數值:
求兩個數的最大公約數和最小公倍數.
提示:最小公倍數=(num1*num2)/最大公約數
本例中用到了python3的內建函式min(a,b),輸出結果就是a和b中的最大值
#1.輸入兩個數值

num1 = int(input('Num1:'))
num2 = int(input('Num2:'))

2.找出兩個數中的最小值

min_num = min(num1,num2)

3.最大公約數的範圍1~min_num之間
最大公約數就是num1和num2能整除的最大的數

for i in range(1,min_num+1): #1,2
	if num1 % i == 0 and num2 % i ==0:
		gys = i

當迴圈結束時存在gys裡的必定是公約數中的最大值
4.最小公倍數

lcm = int((num1*num2)/gys)

print('%s和%s的最大公約數為%s' %(num1,num2,gys))
print('%s和%s的最小公倍數為%s' %(num1,num2,lcm))

在這裡插入圖片描述

range和xrange

python2:
-range(1,5):即刻生成資料,消耗時間並且佔用記憶體
-xrange(1,5):先生成一個xrange物件,使用值的時候才生成資料,才佔用記憶體

python3:
-range(1,5):相當於python2中的xrange

while迴圈

while 條件:
條件滿足時,做的事情1
條件滿足時,做的事情2

1.定義一個整數變數,記錄迴圈次數
i=1
2.開始迴圈
while i<=5:
print (‘hello python’)
# 處理計數器
i += 1

#計算0~100之間的所有偶數累計求和

i = 0
sum = 0

while i <= 100:
	if i % 2 ==0:
		sum += i
	i += 1
print('0~100之間的所有偶數累計求和的結果是 %d' %sum)

#死迴圈

while True:
	print('hello python')

while迴圈練習:
輸出下面圖形:
在這裡插入圖片描述

程式碼:

n=1
while n<=5:
    l=1
    while l<=n:
        print('*',end='')
        l += 1
    print()
    n += 1

print('~~~~~~~~~~~~')

n=1
while n<=5:
    l=5
    while l>=n:
        print('*',end='')
        l -=1
    print()
    n += 1

print('~~~~~~~~~~~~')

n=1
while n<=5:
    l=1
    while l<=5-n:
        print(' ',end='')
        l += 1
    j = 1
    while j<=n and j<=5:
        print('*',end='')
        j +=1
    print()
    n +=1

print('~~~~~~~~~~')

n=1
while n<=5:
    l=1
    while l<n:
        print(' ',end='')
        l+= 1
    while l>=n and l<=5:
        print('*',end='')
        l +=1
print('~~~~~~~~~~')

n=1
while n<=5:
    l=1
    while l<n:
        print(' ',end='')
        l+= 1
    while l>=n and l<=5:
        print('*',end='')
        l +=1
    print()
    n +=1

執行結果:

在這裡插入圖片描述

99乘法表:

i=1
while i<=9:
    j=1
    while j<=i:
        print('{}x{}={}\t'.format(i,j,i*j),end='')
        j +=1
    print()
    i+=1
print('~~~~~~~~~~~~~')
i=1
while i<=9:
    j=9
    while j>=i:
        print('{}x{}={}\t'.format(i,j,i*j),end='')
        j -=1
    print()
    i+=1
print('~~~~~~~~~~~~`')
i=1
while i<=9:
    j=9
    while j>i:
        print('\t',end='')
        j -=1
    while j<=i and j>0:
        print('{}x{}={}\t'.format(i,j,i*j),end='')
        j -=1
    print()
    i +=1
print('~~~~~~~~~~~~~~')
i=1
while i<=9:
    j=1
    while j<i:
        print('\t',end='')
        j +=1
    while j>=i and j<=9:
        print('{}x{}={}\t'.format(i,j,i*j),end='')
        j +=1
    print()
    i +=1
 
                                                                                                                                                                      1,1           All

在這裡插入圖片描述
迴圈練習:
#猜數字遊戲
if , while(for), break
1. 系統隨機生成一個1~100的數字;
** 如何隨機生成整型數, 匯入模組random, 執行random.randint(1,100);
2. 使用者總共有5次猜數字的機會;
3. 如果使用者猜測的數字大於系統給出的數字,列印“too big”;
4. 如果使用者猜測的數字小於系統給出的數字,列印"too small";
5. 如果使用者猜測的數字等於系統給出的數字,列印"恭喜中獎100萬",並且退出迴圈;

程式碼:

import random
a=1
num1=random.randint(1,100)
print(num1)
while a<=5:
    num=int(input('請任意輸入1個1~100的數:'))
    if num>num1:
        print('too big')
        a +=1
    elif num<num1:
        print('too small')
        a +=1
    else:
        print('恭喜中獎100萬')
        break
else:
    print('你的機會用完了!')

為方便測試我們將電腦隨機生成的隨機數打印出來
在這裡插入圖片描述

字串的定義

a = 'hello'
b = "python"
c = """
	使用者管理系統
	1.新增使用者
	2.刪除使用者
	3.顯示使用者
"""
print(type(a))
print(type(b))
print(type(c))
print(a)
print(b)
print(c)
#字串常用的轉義符號
"""
\n:換行
\t:一個tab鍵
\"
\'
"""

#列印guido's
#列印"hello guido's python"

print('guido\'s')
print("guido's")
print('"hello guido\'s python"')
print("\"hello guido's python\"")

print('%s\n%s' %(a,b))
print('%s\t%s' %(a,b))

字串的特性

拿出字串的最後一個字元

print(s[-1])

切片
#s[start:end:step] 從start開始,到end-1結束,步長為step(預設是1)

print('~~~~~~~~~~~~~~~~~~~~~~~~~~')
print(s)
print(s[0:3])
print(s[0:4:2])

顯示所有字元

print(s[:])

顯示前3個字元

print(s[:3])

字串倒序輸出

print(s[::-1])

除了第一個字元之外,其他的全部顯示

print(s[1:])

重複

print(s*10)

連線

print('hello '+'world')

成員操作符

print('he' in s)
print('aa' in s)
print('he' not in s)

字串特性的應用

題目要求:
判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣
的整數。

##示例:

#示例 1:
#輸入: 121
#輸出: true
#示例 2:
#輸入: -121
#輸出: false
#解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數。

#示例 3:
#輸入: 10
#輸出: false
#解釋: 從右向左讀, 為 01 。因此它不是一個迴文數

直接利用python中切片
程式碼:

num=str(input('請輸入一個整數:'))
if num[:]==num[::-1]:
    print('true')
else:
    print('flase')

在這裡插入圖片描述

字串的開頭和結尾的匹配

#匹配字串的開頭和結尾

filename='hello.logggh'
if filename.endswith('.log'):
	print(filename)
else:
	print('error file')

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('不能爬取網頁')

在這裡插入圖片描述

字串去掉兩邊的空格

In [1]: s = '      hello'                                                      

In [2]: s.strip()                                                              
Out[2]: 'hello'

In [3]: s = '      hello      '                                                

In [4]: s.strip()                                                              
Out[4]: 'hello'

In [5]: s.lstrip()                                                             
Out[5]: 'hello      '

In [6]: s.rstrip()                                                             
Out[6]: '      hello'

In [7]: s = '\nhello      '                                                    

In [8]: s.strip()                                                              
Out[8]: 'hello'

In [9]: s = '\thello      '                                                    

In [10]: s.strip()                                                             
Out[10]: 'hello'

In [11]: s = 'helloh'                                                          

In [12]: s.strip('h')                                                          
Out[12]: 'ello'

In [13]: s.strip('he')                                                         
Out[13]: 'llo'

In [14]: s.lstrip('he')                                                        
Out[14]: 'lloh'

In [15]: s.rstrip('he')                                                        
Out[15]: 'hello'

In [17]: print('學生管理系統'.center(50,'*'))                                  
**********************學生管理系統**********************

In [18]: print('學生管理系統'.ljust(50,'*'))                                   
學生管理系統********************************************

In [19]: print('學生管理系統'.rjust(50,'*'))                                   
********************************************學生管理系統

字元的搜尋和替換

find:
replace:
count:

In [20]: s = 'hello python,learn python'                                       

In [21]: s.find('python')                                                      
Out[21]: 6

In [22]: s.rfind('python')                                                     
Out[22]: 19

In [23]: s.replace('python','linux')                                           
Out[23]: 'hello linux,learn linux'

In [24]: s1 = s.replace('python','linux')                                      

In [25]: s1                                                                    
Out[25]: 'hello linux,learn linux'

In [26]: s                                                                     
Out[26]: 'hello python,learn python'

In [27]: s.count('python')                                                     
Out[27]: 2

In [28]: s.count('p')                                                          
Out[28]: 2

In [29]: s.count('i')                                                          
Out[29]: 0

字串的分離和拼接

split:
join:

In [30]: ip = '172.25.254.10'                                                  

In [31]: ip1 = '1172.25.254.10'                                                

In [32]: ip1.split('.')                                                        
Out[32]: ['1172', '25', '254', '10']

In [33]: date = '2018-11-18'                                                   

In [34]: date.split('-')                                                       
Out[34]: ['2018', '11', '18']

In [35]: date.split('.')                                                       
Out[35]: ['2018-11-18']

In [37]: date.replace('-','/')                                                 
Out[37]: '2018/11/18'

In [38]: ip = ['1172', '25', '254', '10']                                      

In [39]: ''.join(ip)                                                           
Out[39]: '11722525410'

In [40]: ':'.join(ip)                                                          
Out[40]: '1172:25:254:10'

In [41]: '*'.join(ip)                                                          
Out[41]: '1172*25*254*10'