python怎么定义用户输入
python中获取用户输入的方法如下:
整数输入
#!/usr/bin/python3
usr_ip=input("Enteranintegernumber:")
#需要将输入的字符串显式地指定为需要的类型
usr_num=int(usr_ip)
sqr_num=usr_num*usr_num
print("Squareofenterednumberis:{}".format(sqr_num))
让我们给定一个整数和字符串来测定这个程序
Pythondocs-整数文本
$./user_input_int.py
Enteranintegernumber:23
Squareofenterednumberis:529
$./user_input_int.py
Enteranintegernumber:abc
Traceback(mostrecentcalllast):
File"./user_input_int.py",line6,in
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
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))
不像Perl,字符串输入不需要进行类型转换和注意换行符
$./user_input_str.py
Hithere!What'syourname?learnbyexample
Andyourfavoritecoloris?blue
learnbyexample,Ilikethebluecolortoo
以上内容为大家介绍了python怎么定义用户输入,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python如何用import语句
Python程序可以调用一组基本的函数(即内建函数),比如print()、input()和len()等函数。Python本身也内置一组模块(即标准库)。每个模块都是一个P...详情>>
2023-11-13 21:55:54
python代码如何运行
交互提示模式下编写代码安装完Python在Windows或Linux中的终端中直接输入python即进入Python交互会话模式。Python交互模式有以下几个注意点:1....详情>>
2023-11-13 20:54:58
python不是内部命令
‘python3’不是内部或外部命令,也不是可运行的程序或批处理文件。我将python安装在D盘之后,输入python,显示如下问题D:\>python'python&...详情>>
2023-11-13 19:50:57
python函数的参数有几种
python中函数的参数可以分为位置参数,关键字参数和默认参数。下面我们一一来讲解。位置参数,有时也称必备参数,指的是必须按照正确的顺序将实...详情>>
2023-11-13 16:42:21