• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python中如何获取用户输入

python 搞java代码 3年前 (2022-05-21) 29次浏览 已收录 0个评论

整数输入

#!/<a href="https://www.gaodaima.com/tag/usr" title="查看更多关于usr的文章" target="_blank">usr</a>/bin/python3
usr_<a href="https://www.gaodaima.com/tag/ip" title="查看更多关于ip的文章" target="_blank">ip</a> = input("Enter an integer <a href="https://www.gaodaima.com/tag/num" title="查看更多关于num的文章" target="_blank">num</a>ber: ")

www#gaodaima.com来源gaodaimacom搞#代%码网搞代码

# 需要将输入的字符串显式地指定为需要的类型

usr_num = int(usr_ip)
sqr_num = usr_num * usr_num
print("Square of entered number is: {}".format(sqr_num))

让我们给定一个整数和字符串来测定这个程序

Python docs – 整数文本

$ ./user_input_int.py
Enter an integer number: 23
Square of entered number is: 529
$ ./user_input_int.py
Enter an integer number: abc
Traceback (most recent call last):
  File "./user_input_int.py", line 6, in <module>
    usr_num = int(usr_ip)
ValueError: invalid literal for int() with base 10: 'abc'

浮点数输入

#!/usr/bin/python3
usr_ip = input("Enter a floating point number: ")
# 需要将输入的字符串显式地指定为我们需要的类型
usr_num = float(usr_ip)
sqr_num = usr_num * usr_num
# 限制小数点位数
print("Square of entered number is: {0:.2f}".format(sqr_num))

E 科学计数法在需要时可以使用

Python文档 – 浮点数文本

Python文档 – 浮点数

$ ./user_input_float.py
Enter a floating point number: 3.232
Square of entered number is: 10.45
$ ./user_input_float.py
Enter a floating point number: 42.7e5
Square of entered number is: 18232900000000.00
$ ./user_input_float.py
Enter a floating point number: abc
Traceback (most recent call last):
  File "./user_input_float.py", line 6, in <module>
    usr_num = float(usr_ip)
ValueError: could not convert string to float: 'abc'

字符串输入

#!/usr/bin/python3
usr_name  = input("Hi there! What's your name? ")
usr_color = input("And your favorite color is? ")
print("{}, I like the {} color too".format(usr_name, usr_color))

不像Perl,字符串输入不需要进行类型转换和注意换行符

$ ./user_input_str.py
Hi there! What's your name? learnbyexample
And your favorite color is? blue
learnbyexample, I like the blue color too

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python中如何获取用户输入

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址