python定义用户输入的方法
小编给大家分享一下python定义用户输入的方法,相信大部分人都还不怎么了解,因此分享这边文章给大家学习,希望大家阅读完这篇文章后大所收获,下面让我们一起去学习方法吧!
Python中获取用户输入的方法如下:
整数输入
#!/usr/bin/python3usr_ip=input("Enteranintegernumber:")
# 需要将输入的字符串显式地指定为需要的类型
usr_num=int(usr_ip)sqr_num=usr_num*usr_numprint("Squareofenterednumberis:{}".format(sqr_num))
让我们给定一个整数和字符串来测定这个程序
Python docs - 整数文本
$./user_input_int.pyEnteranintegernumber:23Squareofenterednumberis:529$./user_input_int.pyEnteranintegernumber:abcTraceback(mostrecentcalllast):File"./user_input_int.py",line6,in<module>usr_num=int(usr_ip)ValueError:invalidliteralforint()withbase10:'abc'
浮点数输入
#!/usr/bin/python3usr_ip=input("Enterafloatingpointnumber:")#需要将输入的字符串显式地指定为我们需要的类型usr_num=float(usr_ip)sqr_num=usr_num*usr_num#限制小数点位数print("Squareofenterednumberis:{0:.2f}".format(sqr_num))
E 科学计数法在需要时可以使用
Python文档 - 浮点数文本
Python文档 - 浮点数
$./user_input_float.pyEnterafloatingpointnumber:3.232Squareofenterednumberis:10.45$./user_input_float.pyEnterafloatingpointnumber:42.7e5Squareofenterednumberis:18232900000000.00$./user_input_float.pyEnterafloatingpointnumber:abcTraceback(mostrecentcalllast):File"./user_input_float.py",line6,in<module>usr_num=float(usr_ip)ValueError:couldnotconvertstringtofloat:'abc'
字符串输入
#!/usr/bin/python3usr_name=input("Hithere!What'syourname?")usr_color=input("Andyourfavoritecoloris?")print("{},Ilikethe{}colortoo".format(usr_name,usr_color))
不像Perl,字符串输入不需要进行类型转换和注意换行符
$./user_input_str.pyHithere!What'syourname?learnbyexampleAndyourfavoritecoloris?bluelearnbyexample,Ilikethebluecolortoo
以上是python定义用户输入的方法的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。