Python内置函数(22)——float

英文文档:

class float([x])

Return a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed:

sign           ::=  "+" | "-"
infinity       ::=  "Infinity" | "inf"
nan            ::=  "nan"
numeric_value  ::=  floatnumber | infinity | nan
numeric_string ::=  [sign] numeric_value

Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity.

Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised.

For a general Python object x, float(x) delegates to x.__float__().

If no argument is given, 0.0 is returned.

 

说明:

  1. 函数功能将一个数值或者字符转换成浮点型数值。

>>> float(3)
3.0
>>> float('3')
3.0

  2. 不提供参数的时候,返回0.0。

>>> float()
0.0

  3. 字符串必须能正确转换成浮点型数值的,否则报错。

>>> float('3.14.15926')
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    float('3.14.15926')
ValueError: could not convert string to float: '3.14.15926'

  4. 字符串中允许出现“+”、“-”两个符号,两个符号和数字之间不能出现空格,但是符号前面和数字后面允许出现空格。

>>> float('+3.14') #带正号
3.14
>>> float('-3.14') #带负号
-3.14
>>> float('  -3.14  ') #正负号前、数字后可以有空格
-3.14
>>> float('- 3.14') #正负号与数字间不可以有空格
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    float('- 3.14')
ValueError: could not convert string to float: '- 3.14'

  5. 有几个特殊的字符串能正确转换,"Infinity"或者“inf”(不区分大小写),能正确转换,表示无穷大,可以和“+”、“-”一起使用;“nan”也能正确转换,表示没有值。

>>> float('Infinity')
inf
>>> float('inf')
inf

>>> float('inFinIty') #不区分大小写
inf

>>> float('+inFinIty') #正无穷
inf
>>> float('-inFinIty') #负无穷
-inf

>>> float('nan') #没有值
nan

  6. 定义的对象如果要被float函数正确转换成浮点数,需要定义__float__函数。

>>> class X:
    def __init__(self,score):
        self.score = score

>>> x = X(9.7)
>>> float(x) #不能转换
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    float(x)
TypeError: float() argument must be a string or a number, not 'X'


>>> class X: #重新定义类,加入__float__方法
    def __init__(self,score):
        self.score = score
    def __float__(self):
        return self.score

>>> x = X(9.7)
>>> float(x) #可以转换
9.7

 

转载于:https://www.cnblogs.com/sesshoumaru/p/6000936.html

### 回答1: Python计算思维训练——输入和错误处理练习(二)涉及的内容是如何处理输入和错误。在Python中,我们经常需要用户输入一些数据来执行特定的计算或操作,但用户可能会输入错误或非预期的数据。因此,我们需要能够正确地处理这些情况,以便程序能够继续执行。 为了处理输入和错误,Python提供了一些内置函数和异常处理机制。其中,一个常用的函数是input(),它用于从用户那里获取输入。我们可以对输入进行验证,以确保它是我们所期望的类型或格式。例如,我们可以使用int()函数将输入转换为整数,如果输入不是整数,则会引发一个异常。为了处理这种异常,我们可以使用try-except块来捕获并处理它。 除了用函数验证输入之外,我们还可以使用条件语句来检查输入是否满足特定的要求。如果输入不符合要求,我们可以提醒用户重新输入或给予错误提示。 另外,Python还提供了一些内置的异常类型,如ValueError、TypeError等,用于处理常见的错误情况。我们可以通过捕获特定的异常类型,并根据需要进行相应的处理。 总之,Python提供了丰富的工具和机制来处理输入和错误。在编写程序时,我们应该合理利用这些工具,以确保我们的程序能够在各种情况下正常运行,而不会因为无效的输入或错误而崩溃。通过训练和练习,我们可以提高我们的计算思维和错误处理能力,使我们的程序更稳健和健壮。 ### 回答2: Python计算思维训练-输入和错误处理练习(二) 在Python中,输入和错误处理是非常重要的技能。它们俩都是帮助我们编写健壮的程序的工具。下面是一些关于这方面的练习和示例。 1. 输入整数: 练习编写一个程序,要求用户输入一个整数,并输出这个整数的平方。同时,需要处理用户输入非整数的情况。 代码示例: ``` while True: try: num = int(input("请输入一个整数: ")) square = num ** 2 print("平方值为: ", square) break except ValueError: print("输入错误,请重新输入一个整数。") ``` 这段代码使用了`try`和`except`语句来捕获可能发生的`ValueError`异常,即用户输入的不是整数。如果发生异常,程序会打印错误信息,并重新提示用户输入直到输入一个正确的整数为止。 2. 输入列表元素: 练习编写一个程序,要求用户输入一系列的数字,并将它们存储在一个列表中。同时,需要检测并处理用户输入非数字的情况。 代码示例: ``` nums = [] while True: try: num = float(input("请输入一个数字(输入字母退出): ")) nums.append(num) except ValueError: print("输入错误,请输入一个数字或字母退出。") continue except KeyboardInterrupt: break print("输入的数字列表为: ", nums) ``` 这段代码使用了`try`和`except`语句来捕获可能发生的`ValueError`异常,即用户输入的不是数字。如果发生异常,程序会打印错误信息,并继续提示用户输入直到输入一个正确的数字或字母为止。同时,使用了`KeyboardInterrupt`异常来响应用户输入字母退出的操作。 这些练习可以帮助你熟悉Python中的输入和错误处理的技巧。当编写程序时,务必记得考虑到用户可能输入非法的情况,使用适当的错误处理机制来增强程序的健壮性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值