python3 中input()
help 信息:
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
input()
讀取的輸入值都會轉化為字符串。
>>> a = input()
123
>>> type(a)
<class 'str'>
如果我們要直接讀取數值可以借助eval()
幫忙。eval(source)
可將source字符串的內容當作python表達式或代碼執行(The source may be a string representing a Python expression or a code object as returned by compile().)
>>> a = eval(input())
123
>>> type(a)
<class 'int'>
>>> print(a)
123
簡單的整型或許可以用工廠函數int()
:
>>> a = int(input())
123
>>> type(a)
<type 'int'>
但是eval()
可以使用一些更復雜的對象,如set集合對象:
>>> a = input()
{1, 3, 4}
>>> type(a)
<class 'str'>
>>> a = eval(input())
{1, 3, 4}
>>> type(a)
<class 'set'>
>>> print(a)
{1, 3, 4}