抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

Sephiroth1s'blog

The quieter you became,the more you are able to hear.

input与raw_input

首先我们我们先聊聊python2和python3使用input中需要注意到的事情

在python2.x中

  • input可以直接接受数字,并返回数字

  • input不可以直接接受字符/字符串

  • 对于input需要使用合法的python表达式才能读入字符串/字符

  • input会把你输入的内容当做python处理,这样会产生安全问题,

    最好使用raw_input!

  • raw_input可以直接读入数字或者字符/字符串,并返回字符串

  • input() 本质上还是使用 raw_input() 来实现的,只是调用完raw_input() 之

    后再调用 eval() 函数,所以,你甚至可以将表达式作为 input() 的参数,并

    且它会计算表达式的值并返回(这段话只要理解前半部分就好了,反正现在

    博主也不懂W( ̄_ ̄)W

在python3.x中

  • 整合了input和raw_input没有raw_input

  • input返回的结果均为字符串

    ———————————————————————–这是一条分割线(~ ̄▽ ̄)~———————————————————————–

下面是相对应的测试代码
python2.x

1.  >>> user=raw_input(“please input:”)
2. please input:wei # raw_input 输入 字符串 成功
3. >>> user
4. ‘wei’
5. >>> user=raw_input(“please input:”)
6. please input:111
7. >>> user
8.111
9. >>> user=input(“please input:”)
10. please input:wei # input 输入字符串 失败
11. Traceback (most recent call last\):
12. File “<stdin>”, line 1, in ?
13. File “<string>”, line 0, in ?
14. NameError: name ‘wei’ is not defined
15. user=input(“please input:”)
16. please input:”wei”      # input 输入字符串
17. >>> user
18. >>>’wei’

python3.x

19.  >>> user=raw_input(“please input:”) #没有了raw_input
20. Traceback (most recent call last):
21. File<stdin>”, line 1, in <module>
22. NameError: name ‘raw_input’ is not defined
23. >>> user=input(“please input:”) please input:wei
24. >>> user
25. ‘wei’
26. >>> user=input(“please input:”) #input的输出结果都是作为字符串
27. please input:123
28. >>> user
29.123