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