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中获取用户输入的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。