如何在Python中獲取整數輸入?
在各種程式設計任務中,獲取整數輸入具有極其重要的意義,Python程式語言提供了多種方法來實現這一目標。本文將深入探討在Python中獲取整數輸入的多種方法,重點介紹以下策略:
揭示`input()`函式和`int()`型別轉換的潛力
利用`map()`函式的多功能性
從檔案源獲取整數輸入
透過命令列引數獲取整數輸入
方法1:揭示`input()`函式和`int()`型別轉換的潛力
`input()`函式是獲取使用者輸入的主要方法之一。它可以從使用者的鍵盤獲取一行輸入,返回一個字串。為了將此字串輸入轉換為整數,可以使用`int()`函式。
示例
在下面的示例中,我們將:
1. 獲取使用者輸入的單個整數,將其儲存在變數'num'中,並列印輸入的值。
2. 獲取多個以空格分隔的整數輸入,將其儲存在列表'nums'中,並列印輸入的值。
示例
# Obtaining a single integer input
num = int(input("Please enter an integer: "))
print("You entered:", num)
# Capturing multiple integer inputs separated by spaces
nums = list(map(int, input("Please enter multiple integers
separated by spaces: ").split()))
print("You entered:", nums)
輸出
Please enter an integer: 5 You entered: 5 Please enter multiple integers separated by spaces: 1 2 3 4 5 You entered: [1, 2, 3, 4, 5]
方法2:利用`map()`函式的多功能性
`map()`函式提供了一種將函式應用於可迭代物件(例如列表或字串)中多個專案的多功能方法。在獲取整數輸入的上下文中,`map()`函式是將`int()`函式應用於包含以空格分隔的整數的字串中的每個專案的有價值工具。
示例
在下面的示例中,我們將:
1. 提示使用者輸入多個以空格分隔的整數,並將它們分割成一個列表。
2. 使用`map()`將列表元素轉換為整數,將其儲存在'nums'中,並列印輸入的值。
示例
# Capturing multiple integer inputs separated by spaces
nums = list(map(int, input("Please enter multiple integers
separated by spaces: ").split()))
print("You entered:", nums)
輸出
Please enter multiple integers separated by spaces: 10 20 30 40 You entered: [10, 20, 30, 40]
方法3:從檔案源獲取整數輸入
在某些情況下,需要從檔案中獲取整數輸入,而不是僅僅依靠使用者輸入。這可以透過使用內建的`open()`函式訪問檔案記錄,並使用`read()`或`readline()`方法檢索其內容來實現。獲取內容後,可以使用`int()`函式將字串表示形式轉換為整數。
示例
在下面的示例中,我們將:
假設有一個名為input.txt的檔案,其中包含以下資料:
5 1 2 3 4 5
下面的程式碼片段從檔案中檢索整數輸入:
1. 開啟“input.txt”檔案進行讀取,獲取單個整數輸入,將其儲存在'num'中並列印該值。
2. 讀取下一行,按空格分割,將元素轉換為整數,將其儲存在'nums'中,並列印整數列表。
示例
# Opening the file for reading
with open("input.txt", "r") as file:
# Retrieving a single integer input
num = int(file.readline().strip())
print("First integer in the file:", num)
# Capturing multiple integer inputs separated by spaces
nums = list(map(int, file.readline().strip().split()))
print("List of integers in the file:", nums)
輸出
First integer in the file: 5 List of integers in the file: [1, 2, 3, 4, 5]
方法4:透過命令列引數獲取整數輸入
命令列引數提供了向Python指令碼提供整數輸入的另一種途徑。`sys.argv`列表包含傳遞給指令碼的命令列引數,指令碼名稱本身位於第一個位置(`sys.argv[0]`)。透過使用`int()`函式,可以將字串引數轉換為整數。
示例
在下面的示例中,我們將建立一個名為`integer_input.py`的Python指令碼,包含以下步驟:
1. 匯入`sys`庫以訪問命令列引數。
2. 將引數轉換為整數,將其儲存在'args'列表中,並列印輸入的值。
示例
import sys
# Attaining integer input from command line arguments
args = [int(arg) for arg in sys.argv[1:]]
print("You entered:", args)
Run the script from the command line with a series of integer arguments:
$ python integer_input.py 10 20 30 40
輸出
You entered: [10, 20, 30, 40]
結論
在本篇全面探討中,我們探索了在Python中獲取整數輸入的多種方法。我們揭示了`input()`函式與`int()`型別轉換的潛力,利用了`map()`函式的多功能性,從檔案源獲取了整數輸入,並透過命令列引數獲取了整數輸入。掌握這些知識後,您可以無縫地在Python中獲取整數輸入,並根據程式設計任務的要求調整您的方法。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP