python输入浮点数_python怎么定义用户输入

5e70d8e24f0c4148.jpg

Python中获取用户输入的方法如下:

整数输入#!/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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值