前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >两天研习Python基础(四) 获取用户输入

两天研习Python基础(四) 获取用户输入

作者头像
王诗翔呀
发布2020-07-02 21:39:26
5620
发布2020-07-02 21:39:26
举报
文章被收录于专栏:优雅R优雅R

今天看到机器之心推送的一个 Python 库 nbdev (https://github.com/fastai/nbdev/)感觉不错,它可以帮助使用者在 Jupyter Notebook 中开发模块和包,为探索性分析与系统的工具构建建立了桥梁,感兴趣的读者不妨一试。

整数输入

代码语言:javascript
复制
#!/usr/bin/python3

usr_ip = input("Enter an integer number: ")

# 需要将输入的字符串显式地指定为需要的类型
usr_num = int(usr_ip)
sqr_num = usr_num * usr_num

print("Square of entered number is: {}".format(sqr_num))
  • 让我们给定一个整数和字符串来测定这个程序
  • Python docs - 整数文本[1]
代码语言:javascript
复制
$ ./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'

浮点数输入

代码语言:javascript
复制
#!/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 科学计数法[2]在需要时可以使用
  • Python文档 - 浮点数文本[3]
  • Python文档 - 浮点数[4]
代码语言:javascript
复制
$ ./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'

字符串输入

代码语言:javascript
复制
#!/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,字符串输入不需要进行类型转换和注意换行符
代码语言:javascript
复制
$ ./user_input_str.py
Hi there! What's your name? learnbyexample
And your favorite color is? blue
learnbyexample, I like the blue color too

参考资料

[1]Python docs - 整数文本: https://docs.python.org/3/reference/lexical_analysis.html#integer-literals

[2]E 科学计数法: https://en.wikipedia.org/wiki/Scientific_notation#E_notation

[3]Python文档 - 浮点数文本: https://docs.python.org/3/reference/lexical_analysis.html#floating-point-literals

[4]Python文档 - 浮点数: https://docs.python.org/3/tutorial/floatingpoint.html

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 优雅R 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 整数输入
  • 浮点数输入
  • 字符串输入
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档