函數input()的工作原理
函數input()讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,python將其存儲在一個變量中,以方便你使用。
#輸入用戶名 username = input("Please input your username:") print (username) #運行結果 Please input your username:Frank Frank
變量傳遞給函數input()
有的時候,我們需要提示的字符串比較長,可以將提示的語句放在一個變量里面。
#greeter prompt = "If you tell us who you are,we can personalize the messages you see." prompt += "\nWhat is your first name?" name = input(prompt) print ("\nhello, " + name + "!") #運行結果 If you tell us who you are,we can personalize the messages you see. What is your first name?Frank hello, Frank!
使用int()來獲取數值輸入
我們input()所得到的是字符串數據,包括你想輸入的整型是123,但是保存到變量里面的時候卻是字符串"123"。
#判斷年齡是否達到做過山車的年齡 age = input("How old are you?") if age >=18: print("You can ride!") else: print("You can't ride ") #運行結果,當我們不使用int()把字符串轉為整型的話,age是不能和數值18比較的 TypeError: '>=' not supported between instances of 'str' and 'int'
所以需要使用函數int()
#判斷年齡是否達到做過山車的年齡 age = input("How old are you?") if int(age) >=18: print("You can ride!") else: print("You can't ride ") #運行結果 How old are you?18 You can ride!
求模運算符
處理數值信息時,求模運算符(%)是一個很有用的工具,它將兩個數相除並返回余數:
>>> 4 % 3
1
>>> 5 % 3
2
>>> 6 % 3
0
>>> 7 % 2
1
可以用來判斷奇偶數。
python2中的raw_input()
在python2中使用raw_iput()來提示用戶輸入,這個與python3中的input()是一樣的,也將輸入解讀為字符串。python2中也存在input(),但它將用戶輸入解讀為python代碼,並嘗試執行它。
username = raw_input("Please input your username:") print (username) username = input("Please input your username:") print (username) #運行結果 Please input your username:cisco cisco Please input your username:cisco Traceback (most recent call last): File "C:\Python27\test.py", line 3, in <module> username = input("Please input your username:") File "<string>", line 1, in <module> NameError: name 'cisco' is not defined
我們會看到在python2中使用raw_input可以正常輸出,但是使用input就不能正常輸出的,因為他把你輸入的當做可執行的代碼。
while循環
while循環不斷地運行,直到指定的條件不滿足為止。
#輸出1-5 current_number = 1 while current_number <= 5: print(current_number) current_number+=1 #運行結果 1 2 3 4 5
使用標志
有的時候使用標志可以簡化while的語句,因為不需要在其中做任何比較--相關的邏輯由程序的其他部分處理。
#quit退出 prompt = "\nTell me something,and i will repeat it back to you:" prompt += "\nEnter 'quit' to end the program. " active = True while active: message = input(prompt) if message == 'quit': active = False else: print(message) #運行結果 Tell me something,and i will repeat it back to you: Enter 'quit' to end the program. hello! hello! Tell me something,and i will repeat it back to you: Enter 'quit' to end the program. my name is Frank my name is Frank Tell me something,and i will repeat it back to you: Enter 'quit' to end the program. quit
break和continue
break:會結束本層循環,不再運行循環中余下的代碼;
continue:結束本次循環,僅僅結束一次循環,不再運行本次余下的代碼。
#break舉例 current_number = 1 while current_number < 10: if current_number == 5: current_number+=1 break else: print(current_number) current_number+=1 #運行結果 1 2 3 4 #continue舉例 current_number = 1 while current_number < 10: if current_number == 5: current_number+=1 continue else: print(current_number) current_number+=1 #運行結果 1 2 3 4 6 7 8 9