每日一课 | 读取浮点数

要使用Python进行输入,我们使用input()函数 ,它要求用户输入并返回字符串值,无论输入了什么值,所有值都将被视为字符串值。

考虑以下示例:

# python code to demonstrate example
# of input() functionval1 = input("Enter any value: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1)) val2 = input("Enter another value: ")
print("value of val2: ", val2)
print("type of val2: ", type(val2)) val3 = input("Enter another value: ")
print("value of val3: ", val3)
print("type of val3: ", type(val3))

输出量

Enter any value: 10
value of val1: 10
type of val1: 
Enter another value: 10.23
value of val2: 10.23
type of val2: 
Enter another value: Hello
value of val3: Hello
type of val3: 

参见程序和输出–在这里,我们为val1提供了三个值“ 10” ,它是一个整数值,但被视为字符串,为val2提供了 “ 10.23” ,它是一个浮点值,但被视为一个字符串,为val3提供了 “ Hello” ,其中是一个字符串值。

如何将输入作为浮点数?

没有这样的方法,可以使用它直接将输入作为浮点数,但是可以使用float()函数将输入字符串转换为浮点数,该函数接受一个字符串或数字并返回一个浮点值。

因此,我们使用input()函数读取输入,并使用float()函数将其转换为float。

考虑下面的示例:

# python code to take float input# reading a value, printing input and it's type
val1 = input("Enter any number: ")
print("value of val1: ", val1)
print("type of val1: ", type(val1)) # reading a value, converting to float
# printing value and it's type
val2 = float(input("Enter any number: "))
print("value of val2: ", val2)
print("type of val2: ", type(val2))

输出量

Enter any number: 123.456
value of val1: 123.456
type of val1: 
Enter any number: 789.123
value of val2: 789.123
type of val2: 

输入两个浮点数并找到它们的和与平均值的示例

# python code to read two float numbers
# and find their addition, averagenum1 = float(input("Enter first number : "))
num2 = float(input("Enter second number: ")) # addition
add = num1 + num2 # average
avg = add/2print("addition: ", add)
print("average : ", avg)

输出量

Enter first number : 123.456
Enter second number: 789.02
addition: 912.476
average : 456.238


翻译自: https://www.includehelp.com/python/read-input-as-a-float.aspx

推荐阅读--

每日一课 | python逐行处理文件

每日一课 | python条件语句多条件

每日一课 | Python保存程序

每日一课 | python 元组解构赋值

球分享

球点赞

球在看


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部