资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

python中获取用户输入的方法

小编给大家分享一下python中获取用户输入的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

创新互联公司"三网合一"的企业建站思路。企业可建设拥有电脑版、微信版、手机版的企业网站。实现跨屏营销,产品发布一步更新,电脑网络+移动网络一网打尽,满足企业的营销需求!创新互联公司具备承接各种类型的成都做网站、网站制作项目的能力。经过10多年的努力的开拓,为不同行业的企事业单位提供了优质的服务,并获得了客户的一致好评。

整数输入

#!/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 - 整数文本

$ ./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 
    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 
    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

看完了这篇文章,相信你对python中获取用户输入的方法有了一定的了解,想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


分享标题:python中获取用户输入的方法
标题网址:http://cdkjz.cn/article/jgopdc.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220