python3 eval(input())


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}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM