开发人员经常需要与用户交互,以获取数据或提供某种结果。如今,大多数程序都使用对话框来要求用户提供某种类型的输入。而Python为我们提供了两个内置函数来读取键盘输入。
- input ( prompt )
- raw_input ( prompt )
input():该函数首先获取用户的输入并将其转换为字符串。返回对象的类型始终为<class ‘str’>。它不会计算表达式,只是将完整的语句作为字符串返回。例如,Python 提供了一个名为 input 的内置函数,它接受用户的输入。当调用输入函数时,它会停止程序并等待用户的输入。当用户按下回车键时,程序将恢复并返回用户输入的内容。
inp = input('STATMENT')
示例:
1. >>> name = input('你的名字是说明?\n') # \n ---> newline ---> 它会导致换行
>>> 你的名字是什么?
Ram
>>> print(name)
Ram
# ---> python 中的注释
# Python program showing
# a use of input()
val = input("Enter your value: ")
print(val)
输出:
以 String 作为输入:
name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
print(name)
输出:
What is your name?
Ram
Ram
输入函数在 Python 中的工作原理:
- 当 input() 函数执行时,程序流将停止,直到用户给出输入。
- 显示在输出屏幕上要求用户输入输入值的文本或消息是可选的,即打印在屏幕上的提示是可选的。
- 无论您输入什么内容,输入函数都会将其转换为字符串。如果您输入一个整数值,input() 函数仍然会将其转换为字符串。您需要使用类型转换在代码中将其显式转换为整数。
# Program to check input
# type in Python
num = input ("Enter number :")
print(num)
name1 = input("Enter name : ")
print(name1)
# Printing type of input value
print ("type of number", type(num))
print ("type of name", type(name1))
输出:
Enter number :123
Enter name : Lily
Lily
type of number <class 'str'>
type of name <class 'str'>
raw_input():该函数适用于旧版本(如Python 2.x)。该函数准确获取从键盘输入的内容,将其转换为字符串,然后将其返回到我们要存储它的变量。
例子:
# Python program showing
# a use of raw_input()
g = raw_input("Enter your name : ")
print g
输出:
Enter your name : jkhxw
jkhxw
这里,g是一个变量,它将获取用户在程序执行期间键入的字符串值。raw_input() 函数的数据输入由 Enter 键终止。我们也可以使用 raw_input() 输入数字数据。在这种情况下,我们使用类型转换。
有多种函数可用于获取所需的输入:
- int(input())
- float(input())
num = int(input("Enter a number: "))
print(num, " ", type(num))
floatNum = float(input("Enter a decimal number: "))
print(floatNum, " ", type(floatNum))
输出: