1. 函數input() 的工作原理 函數input() 讓程序暫停運行,等待用戶輸入一些文本。獲取用戶輸入后,Python將其存儲在一個變量中.
message = input("Tell me something, and I will repeat it back to you: ")PRint(message)(1). 使用int() 來獲取數值輸入 使用函數input() 時,Python將用戶輸入解讀為字符串。
>>> age = input("How old are you? ")How old are you? 21>>> age'21'函數int() 將數字的字符串表示轉換為數值表示
height = input("How tall are you, in inches? ")height = int(height)if height >= 36: print("/nYou're tall enough to ride!")else: print("/nYou'll be able to ride when you're a little older.")(2).求模運算符 處理數值信息時,求模運算符 (%)是將兩個數相除并返回余數
number = input("Enter a number, and I'll tell you if it's even or odd: ")number = int(number)if number % 2 == 0: print("/nThe number " + str(number) + " is even.")else: print("/nThe number " + str(number) + " is odd.")2. while 循環簡介 (1).使用while 循環
current_number = 1while current_number <= 5: print(current_number) current_number += 1(2).使用break 退出循環 要立即退出while 循環,不再運行循環中余下的代碼,也不管條件測試的結果如何,可使用break 語句。
prompt = "/nPlease enter the name of a city you have visited:"prompt += "/n(Enter 'quit' when you are finished.) "while True: city = input(prompt) if city == 'quit': break else: print("I'd love to go to " + city.title() + "!")(3).在循環中使用continue 要返回到循環開頭,并根據條件測試結果決定是否繼續執行循環,可使用
continue 語句current_number = 0while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number)新聞熱點
疑難解答