接受輸入是一種與用戶互動的方式,或者獲取數據以提供某種結果。Python 提供了兩種內置的方法從鍵盤讀取數據。下面給出了這些方法。
- 輸入(提示)
- 原始輸入(提示)
輸入()
所有最新版本的 Python 中都使用了輸入函數。它接受用戶的輸入,然后計算表達式。 Python 解釋器自動識別用戶輸入的是字符串、數字還是列表。讓我們理解下面的例子。
示例-
# Python program showing
# a use of input()
name = input("Enter your name: ")
print(name)
輸出:
Enter your name: Devansh
Devansh
在用戶輸入之前,Python 解釋器不會執行更多的行。
讓我們理解另一個例子。
示例- 2
# Python program showing
# a use of input()
name = input("Enter your name: ") # String Input
age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input
print("The name is:", name)
print("The age is:", age)
print("The marks is:", marks)
輸出:
Enter your name: Johnson
Enter your age: 21
Enter your marks: 89
The name is: Johnson
The age is 21
The marks is: 89.0
說明:
默認情況下, input() 函數將輸入作為字符串,因此如果我們需要輸入整數或浮點類型的輸入,那么 input() 函數必須是類型鑄造的。
age = int(input("Enter your age: ")) # Integer Input
marks = float(input("Enter your marks: ")) # Float Input
我們可以在上面的代碼中看到,我們將用戶輸入輸入到 int 和 float 中。
input()函數是如何工作的?
- 在用戶輸入之前,程序的流程已經停止。
- 也稱為提示的文本語句可選擇寫入輸入()功能。該提示將在控制臺上顯示消息。
- 輸入()功能自動將用戶輸入轉換為字符串。我們需要使用類型轉換來顯式轉換輸入。
- raw _ input()-raw _ input 函數用于 Python 的舊版本,比如 Python 2.x,它從鍵盤上獲取輸入,并以字符串形式返回。Python 2.x 在業內使用不多。讓我們理解下面的例子。
示例-
# Python program showing
# a use of raw_input()
name = raw_input("Enter your name : ")
print name
輸出:
Enter your name: Peter
Peter
如何查看 Python 版本?
要檢查 Python 版本,打開命令行(Windows)、shell (Mac)或終端(Linux/Ubuntu),運行 python -version 。它將顯示相應的 Python 版本。
查看運行腳本中的 Python 版本
我們可以在運行腳本中檢查 Python 版本??紤]以下方法來了解所有操作系統中的 Python 版本。
| 命令 | 操作系統/環境 | 輸出 | | Python 版本或 Python -v 或 Python -vv | 視窗/蘋果/Linux | Python 3.8.1 | | 導入系統 系統版本 系統版本 _ 信息 | Python 腳本 | 3.8.3(默認,2020 年 5 月 13 日 15:29:51) [MSC v.1915 64 位(AMD64)] | | 導入平臺 platform.python_version() | Python 腳本 | '3.8.1' |
讓我們看看下面的圖片。