Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

22. Python 输入

在本教程中,我们将学习最常见的函数input() that we use frequently to take keyboard input from the user from the console. In our many tutorial we have used this, today we will see python input function more closely.

Python输入()

Python中有Python输入函数builtins.py. It reads a string from standard input and the trailing newline is stripped.

input() statement is executed then the program get paused until user gives the input and hit the enter key.

input() returns the string that is given as user input without the trailing newline.

Python获取用户输入

让我们看一个使用python输入函数获取用户输入的简单示例。


# taking an input from the keyboard
a = input()

# taking another input from the keyboard
b = input()

c = a + b
print("a + b = %s + %s = %s" % ( a, b, c ))

这将输出:


45
12 
a + b = 45 + 12  = 4512 

哎呀!输出是什么?45加12等于4512??因为input()方法返回字符串从键盘输入得到的。要执行我们真正想要的操作,我们必须按如下方式将其转换为整数:


c = int(a) + int(b)

现在它将输出:


45
12
a + b = 45 + 12 = 57

所以,在接受输入后,按照您想要的方式进行转换。

带字符串消息的Python输入函数

在上面的例子中,我们没有得到我们应该做什么的任何提示。为了向用户提供说明,我们可以输入以下内容:


a = input("Please Enter the first number = ")
b = input("Enter the second number = ")
c = int(a) + int(b)
print("Summation of a + b = %s + %s = %s" % ( a, b, c ))

这将输出:


Please Enter the first number = 45
Enter the second number = 12
Summation of a + b = 45 + 12 = 57

另一个简单的Python用户输入示例

下面的例子以用户名为例,找出其中元音的出现次数。


# taking input from prompt
name =input("what is your name? ")
print("Hello %s" % name)

# taking a counter to count the vowels
count = 0
for i in name:
   i = i.capitalize()
   if i == "A" or i == "E" or i == "I" or i == "O" or i == "U":
       count = count + 1

print("Your name contains %s vowels" % count)

这将输出:

还有一件事我应该提到Pythoninput function is that it raises an error if the user hits EOF ( for *nix: Ctrl-D, Windows: Ctrl-Z+Return). The raised error is EOFError. In the above example if you press Ctrl-D then you will see the output as:


what is your name? ^D
Traceback (most recent call last):
  File "D:/T_Code/PythonPackage3/Input.py", line 2, in 
    name =input("what is your name? ")
EOFError: EOF when reading a line

这是关于python输入函数和如何在python中获得用户输入的快速综述。