![图片[1]-python中如何获取用户输入-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d297f4a14894216.jpg)
整数输入
#!/usr/bin/python3
usr_ip=input("Enteranintegernumber:")
# 需要将输入的字符串显式地指定为需要的类型
usr_num=int(usr_ip)
sqr_num=usr_num*usr_num
print("Squareofenterednumberis:{}".format(sqr_num))
让我们给定一个整数和字符串来测定这个程序
Python docs – 整数文本
$./user_input_int.py Enteranintegernumber:23 Squareofenterednumberis:529 $./user_input_int.py Enteranintegernumber:abc Traceback(mostrecentcalllast): File"./user_input_int.py",line6,in<module> usr_num=int(usr_ip) ValueError:invalidliteralforint()withbase10:'abc'
浮点数输入
#!/usr/bin/python3
usr_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.py Enterafloatingpointnumber:3.232 Squareofenterednumberis:10.45 $./user_input_float.py Enterafloatingpointnumber:42.7e5 Squareofenterednumberis:18232900000000.00 $./user_input_float.py Enterafloatingpointnumber:abc Traceback(mostrecentcalllast): File"./user_input_float.py",line6,in<module> usr_num=float(usr_ip) ValueError:couldnotconvertstringtofloat:'abc'
字符串输入
#!/usr/bin/python3
usr_name=input("Hithere!What'syourname?")
usr_color=input("Andyourfavoritecoloris?")
print("{},Ilikethe{}colortoo".format(usr_name,usr_color))
$./user_input_str.py Hithere!What'syourname?learnbyexample Andyourfavoritecoloris?blue learnbyexample,Ilikethebluecolortoo原文来自:https://www.py.cn
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容