1. 通过help函数查看input的docstring
1 # 1. 通过内置函数help查看input函数的docstring 2 ''' 3 input(prompt='', /) 4 Read a string from standard input. The trailing newline is stripped. 5 6 The prompt string, if given, is printed to standard output without a 7 trailing newline before reading input. 8 9 If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. 10 On *nix systems, readline is used if available. 11 ''' 12 help(input)
2. input函数的使用说明
input()
函数是Python内置函数,用于从标准输入读取一个字符串。以下是input()
函数的详细说明:
1 input(prompt='', /)
prompt
(可选参数):用于指定在读取输入之前要打印到标准输出的提示字符串。默认为空字符串。
input()
函数的工作原理如下:
- 首先,它会将
prompt
参数的值打印到标准输出,提示用户输入。 - 然后,它从标准输入读取用户的输入,并返回一个字符串,会自动去掉末尾的换行符。
input()
函数提供一些特殊操作和异常处理:
- 如果用户按下EOF(在Unix系统中是Ctrl-D,Windows系统中是Ctrl-Z+回车),则会引发
EOFError
异常。 - 在Unix系统上,如果可用,会使用
readline
库来提供更高级的文本编辑功能。1 name = input("请输入你的名字:") 2 age = input("请输入你的年龄:") 3 print(type(name)) 4 print(type(age)) # 在等待用户输入时,用户敲了ctrl + D,就会触发EOFError错误
这些说明解释了input()
函数的用法、行为和异常处理。你可以根据需要使用prompt
参数来自定义提示信息。要处理EOFError
异常,你可以使用try-except
结构来捕获它并进行相应的处理。
3. 示例
1 ''' 2 input是程序与人交换的桥梁 3 遇到input函数,程序就会等待用户的输入,敲回车结束等待 4 input会把用户的输入转变为python中的字符串对象 5 ''' 6 7 # 1. 通过内置函数help查看input函数的docstring 8 ''' 9 input(prompt='', /) 10 Read a string from standard input. The trailing newline is stripped. 11 12 The prompt string, if given, is printed to standard output without a 13 trailing newline before reading input. 14 15 If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError. 16 On *nix systems, readline is used if available. 17 ''' 18 help(input) 19 20 # 2. 提示语 & 返回类型(字符串类型) 21 name = input("请输入你的名字:") 22 age = input("请输入你的年龄:") 23 print(type(name)) # <class 'str'> 24 print(type(age)) # <class 'str'> 25 26 # 3. input函数返回值类型为str,实际研发中需要转换为其他类型 27 age = int(input("请输入您的年龄:")) # 字符串类型转换为int类型 28 print("您的年龄是:", age) 29 30 # 4. 提示信息 + 数据类型转换 + 异常处理 31 ''' 32 crtl + D报错信息 33 Traceback (most recent call last): 34 File "F:\allen_class\python\base\013内置函数input.py", line 41, in <module> 35 print("您输入的数字是:", num) 36 ^^^ 37 NameError: name 'num' is not defined. Did you mean: 'sum'? 38 ''' 39 while True: 40 try: 41 num = float(input("请输入一个数字:")) 42 break 43 except ValueError: 44 print("输入有误,请重新输入。") 45 except EOFError: 46 print("请不要敲crtl + D") 47 # continue # 无法进入下一轮迭代 48 break 49 print("您输入的数字是:", num)
4. 最佳实践
在使用 Python 中的 input()
函数时,以下是一些最佳实践:
-
提供良好的提示信息:在调用
input()
函数之前,最好提供一个清晰明确的提示信息,以便用户知道他们需要输入什么。例如:name = input("请输入您的姓名:")
。 -
处理输入类型错误:
input()
函数始终返回字符串,无论用户输入是什么类型。如果你期望输入一个数字,你可能需要将返回的字符串转换为相应的数据类型。例如:age = int(input("请输入您的年龄:"))
。 -
异常处理:在处理用户输入时,要考虑可能发生的异常情况。例如,用户可能输入一个无效的数字字符串,或者在输入过程中意外中断。使用
try-except
块来捕获可能引发的异常并进行适当的处理。 -
输入验证:根据程序的需求,可以对用户输入进行一些验证。例如,如果需要一个正整数输入,可以添加一个验证步骤确保用户输入的是一个有效的正整数。
-
提供容错机制:考虑到用户可能会输入无效的或者意外的内容,你可以提供适当的容错机制来处理这些情况。例如,给出一个错误消息并要求用户重新输入。
总的来说,最佳的实践是根据你的需求来合理使用 input()
函数,并在代码中添加适当的错误处理和验证步骤,以提高用户体验并确保程序的稳定性。