哈嘍兄弟們,本節咱們來復習一下用戶輸入和while回圈,
函式input()的作業原理
函式input()讓程式暫停運行,等待用戶輸入一些文本,獲取用戶輸入后,python將其賦值給一個變數,以方便繼續使用,
例如我們嘗試讓用戶輸入一些東西
a = input("請輸入一個數")
print(a)
運行結果
請輸入一個數
這時我們就可以根據要求輸入數值
函式input()接受一個引數——要向用戶顯示的提示或說明,讓用戶知道該怎么做,
使用int()來獲取數值輸入
使用函式input()時,python將用戶輸入解讀為字串,
下列將演示用戶輸入某編號,
a = int(input("請輸入編號")) print(a)
運行結果
請輸入編號
除了int的資料型別,我們還可以根據需要從而輸入不同的資料型別,
同時加之運算子的使用,可以滿足我們更多的需求,
while回圈簡介
for回圈用于針對集合中的每個元素都執行一個代碼塊,而while回圈則不斷運行,直到指定的條件不滿足為止,
下列我們簡單的來用while回圈數數,
a = 1 while a<=5: print(a) a+=1
運行結果
1 2 3 4 5
可以清晰的看出,while當滿足他的回圈條件時,會停止運行!
根據上述我們所學習到的知識我們可以嘗試著讓用戶選擇何時退出程式!
tellme = "tell me something about you,and i will repeat it back toyou" tellme == "if you have anything to say,please continue!\nif you have anything to say,please input quit" message = " " while message !="quit": message = input(tellme) print(message)
運行結果
tell me something about you,and i will repeat it back to youi i tell me something about you,and i will repeat it back to youlove love tell me something about you,and i will repeat it back to youyou you tell me something about you,and i will repeat it back to youquit quit 行程已結束,退出代碼0
使用break退出回圈
要想立即退出回圈,不在運行回圈中的余下代碼,也不管條件測驗的結果如何,直接退出回圈,就可以用到break陳述句,控制程式流程,可以控制那些代碼可以執行,哪些代碼不可以執行,
請欣賞以下代碼:
tellme = "\ntell me something about you,and i will repeat it back to you" tellme += "\nif you have anything to say,please continue!\nif you have anything to say,please input quit\t" while True: yousay = input(tellme) if yousay == "quit": break else: print(f"thank you") # Python資料原始碼自取君羊 708525271
運行結果
tell me something about you,and i will repeat it back to you if you have anything to say,please continue! if you have anything to say,please input quit i love you thank you tell me something about you,and i will repeat it back to you if you have anything to say,please continue! if you have anything to say,please input quit quit 行程已結束,退出代碼0
在回圈中使用continue
要回傳回圈開頭,并根據條件測驗結果決定是否繼續執行回圈,可以使用continue陳述句,它不像break陳述句不在執行余下2代碼·并退出整個回圈,
例如我們列印從1到10但是只列印其中的奇數的回圈,
a = 0 while a < 10: a += 1 if a%2 == 0: continue print(a)
運行結果
1 3 5 7 9
首先將a設定為0,python進入回圈while后,以步長為1增加,接下來,if陳述句檢查a與2求模運算結果,如可以被整除,就執行continue陳述句,忽略余下代碼,并回傳開頭,反之,列印
避免無限回圈
每一個while陳述句的必須要有其結束的條件,否則它將永遠的回圈下去!
洗掉為特定值的所有元素
在我們之前學習中使用函式remove()函式用來洗掉串列中的特定值,
這之所以可行,是因為要洗掉的值只在串列中出現一次,
如果我們要洗掉串列中的所有數值4那該怎么辦呢?
a = [4,596,42,59,44,36,4,12,234,59] print(a) while 4 in a: a.remove(4) print(a)
運行結果
[4, 596, 42, 59, 44, 36, 4, 12, 234, 59]
[596, 42, 59, 44, 36, 12, 234, 59]
洗掉的是數值4,并不是包含4的所有數值,
最后
# 兄弟們學習python,有時候不知道怎么學,從哪里開始學,掌握了基本的一些語法或者做了兩個案例后,不知道下一步怎么走,不知道如何去學習更加高深的知識, # 那么對于這些大兄弟們,我準備了大量的免費視頻教程,PDF電子書籍,以及源代碼!直接在這個群 708525271 自取就好啦! # 還會有大佬解答!
好了,今天的分享到這里差不多就結束了,最后給大家分享一套Python教程:
Python零基礎入門全套教程
Python進階全套教程
Python實戰100例
人生苦短,我用Python!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/531806.html
標籤:其他
上一篇:04python基礎知識02
