python3的input函数特性
python3与python2的input的区别
使用注意
引例
pwd_list=['20201234','20201235','20201236'] def account_login(): ID=int(input('please input your ID:')) password = input('Password:') if password == pwd_list[ID] : print('login success!') else: new_pwd=input('enter a new pwd:') pwd_list[ID]=new_pwd print('changed') account_login() account_login()我在练习使用python的if结构做登录函数时,出现了问题,通过修改python2还有python3run code找到了区别,上面的例子已经使用了int()转型,是没有问题的。
如果仅使用input输入ID的话,python3运行就会出错,如下
File "/Users/user/存储D/python/02-login_test.py", line 5, in account_login if password == pwd_list[ID] : TypeError: list indices must be integers or slices, not str之前学过的c++,还有java,都是先定义变量类型,再使用。
python呢,就比较简洁,直接赋值,根据你值的类型,给变量定型,很符合心意,所以我用input的时候没想那么多,然后一查资料才知道,Python3的input函数默认返回值都为str。
python3的input函数特性
Python3 中 input() 函数接受一个标准输入数据,返回为 string 类型,即把任何输入看作str。
即其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。
详情可以终端打开交互模式,输入help(input)查看
python3与python2的input的区别
在python2中有input和raw_input两个函数,其中raw_input将所有输入作为字符串看待,返回字符串类型。
input函数支持表达式、数字类型、字符串类型,接受为表达式时,只返回其执行结果。
在 Python3中 raw_input() 和 input() 进行了整合,去除了 raw_input( ),仅保留了input( )函数,并且将其改变成了现在的用法。
使用注意
牢记其返回值为str的特性,在一些用与输入比较,或者匹配的时候,一定要依据具体情况作出相应的改变
数据类型处理方法
Int() str() float()等
>>> a=input('please input number:') please input number:666 >>> a '666' >>> a=int(input('please input number:')) please input number:666 >>> a 666