從零開始學Python(第三天)


在這裏插入圖片描述

第三天

在第二天的鞏固練習時,已經使用到了大量的循環語句,此篇文章就是來加強循環的使用的

循環就是重複執行的代碼

3.1 while循環加強

while循環的基礎使用

#求 0~100以內的偶數?
a = 0
while a<101:
	if a%2 == 0:
		print("%s是偶數"%a)
	if a %2 == 1:
		print("{}是奇數".format(a))
	a+=1
	
#100~300以內奇數的和?
a = 100
add = 0
while a<=300:
	if a%2 != 0:
		add+=a
	a+=1
print("100-300間奇數的和是: ",add)

3.1.1 break、continue關鍵字

​ break 是解釋當前循環,只能中止距他最近的一次循環
​ continue是結束本次循環門進入下次循環

請根據下面的實例來詳細瞭解這兩個關鍵字,因爲及其重要

while循環加強
while condition:
循環體
[else:
循環正常執行完成後,才執行的;若else沒有被打斷,就會執行
如果循環被非正常終止,則不會執行else中的代碼;被break打斷後就不會只執行else
]

舉例:

#代碼
num = 5
while num > 1:
	num -= 1
	print("num的值是{}\t".format(num))
else:
	print("循環正常執行完成後,打印此句話")
#執行代碼
D:\網絡安全\Python\py_code>python Class3_while循環加強.py
num的值是4
num的值是3
num的值是2
num的值是1
循環正常執行完成後,打印此句話

#若添加break的跳出語句,則會導致與while配套的額else不會執行
num = 5
while num > 1:
	num -= 1
	print("num的值是{}\t".format(num))
	if num == 3:
		print("由於循環被打斷中止了,所以打印此句話!")
		break
else:
	print("循環正常執行完成後,打印此句話")
#代碼執行
D:\網絡安全\Python\py_code>python Class3_while循環加強.py
num的值是4
num的值是3
由於循環被打斷中止了,所以打印此句話!

3.1.2 random模塊介紹

|-- 隨機數 random模塊	僞隨機
		import random
		random.randint(a, b)
		random.random()		# 返回[0~1)的隨機數
		使用dir()來獲取某些系統庫函數的方法
		使用help()來獲得某些方法如何使用

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random.randint)
Help on method randint in module random:

randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.
>>>

小試牛刀:

#完成以下直角三角形的打印
*
**
***
****
*****
index = 1
vol = int(input("please input your hangshu: "))
#從1開始到用戶輸入的數字結束,表示打印出來的行數
while index <= vol:
	#內部循環用於打印*,但是要根據第幾行來決定打印*的數量
	sec = 1
	#內部循環從1開始到行數結束,第幾行就打印幾個*
	while sec <= index:
		print("*",end="") #注意不能換行
		#控制內部循環終止的條件
		sec += 1
	#控制外部循環終止的條件
	index += 1
	print("") #注意,外部循環,即每打印一行是要進行換行的
#執行代碼
D:\網絡安全\Python\py_code>python Class3_直角三角形的打印.py
please input your hangshu: 5
*
**
***
****
*****

注意:在程序中,數字0表示假,非零即真,空字符串表示假,其他表示真;None;False

3.2 for循環

for 循環
python的中的for循環本質就是用來迭代數據的 可迭代對象(Iterable對象)

python中的for循環本質是用來迭代可迭代對象

​ 舉例:列表的遍歷 ls是一個列表,後面會詳細介紹

ls = ["1","2","3"]

for u in ls:

	print(u,end="") #print()函數默認是換行的,將end參數設置爲空,則就不會換行

#輸出的內容是
123

3.2.1 range函數

range()函數的使用
​ range(n) 表示一個區間範圍的遞增的數據 [0, n)
​ range(m, n) 表示一個區間範圍,[m, n)的區間
​ range(m, n, s) 第三個值表示步長step

幫助文檔

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |
 |  Return an object that produces a sequence of integers from start (inclusive)
 |  to stop (exclusive) by step.  range(i, j) produces i, i+1, i+2, ..., j-1.
 |  start defaults to 0, and stop is omitted!  range(4) produces 0, 1, 2, 3.
 |  These are exactly the valid indices for a list of 4 elements.
 |  When step is given, it specifies the increment (or decrement).
 翻譯一下
 
>>>幫助(範圍)

模塊內置中有關類範圍的幫助:


類範圍(對象)

|範圍(停止)->範圍對象

|範圍(開始,停止[,步驟]->範圍對象

|

|返回一個對象,該對象從一開始就生成一個整數序列(包括)

|一步一步地停止(排除)。範圍(i,j)產生i,i+1,i+2,…,j-1。

|開始默認爲0,停止被忽略!範圍(4)產生0、1、2、3。

|這些正是4個元素列表的有效索引。

|當給定step時,它指定增量(或減量)。 
課堂小練習:
#完成99乘法表
1x1=1
1x2=2 2x2=4
...
1x9=9 2x9=18 ... 9x9=81

#控制輸出的行數 9行 1-9
for i in range(1,10):
	#控制每行輸出的內容 從1開始到本行的大小結束
	for j in range(1,i+1):
		print("{}x{}={}".format(j,i,i*j),end="\t")
	#每輸出一行換行
	print()
程序執行輸出如下
1x1=1
1x2=2   2x2=4
1x3=3   2x3=6   3x3=9
1x4=4   2x4=8   3x4=12  4x4=16
1x5=5   2x5=10  3x5=15  4x5=20  5x5=25
1x6=6   2x6=12  3x6=18  4x6=24  5x6=30  6x6=36
1x7=7   2x7=14  3x7=21  4x7=28  5x7=35  6x7=42  7x7=49
1x8=8   2x8=16  3x8=24  4x8=32  5x8=40  6x8=48  7x8=56  8x8=64
1x9=9   2x9=18  3x9=27  4x9=36  5x9=45  6x9=54  7x9=63  8x9=72  9x9=81

3.2.2 兩種循環的比較與總結

​ 在程序設計開發的過程中,作爲程序最基本的選擇結構和循環結構,編寫基礎代碼的過
程中,佔據了非常重要的地位,對這兩部分的內容的操作要非常熟練。

選擇結構
python 只是提供了一種 if 選擇結構,極大程度的簡化了根據條件進行不同數據處理邏輯的控制
循環結構
➢ python 提供了 for…in 循環結構和 while 循環結構
➢ for…in 循環結構注重於對固定數據列表的循環遍歷和使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章