您的位置:

Python 中如何获取输入?

接受输入是一种与用户互动的方式,或者获取数据以提供某种结果。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' |

让我们看看下面的图片。