python

时间:2018-11-17 05:36:22

标签: python python-3.x

这是代码

import pydoc
def read_float(prompt):
    while True:
        try:
            number_text = read_text(prompt)
            result = float(number_text)
            break
        except ValueError:
            print('Enter a number')
    return result
read_float(1)

我正在尝试在此图像的python中使用read_text函数read_text program

但是在终端中我未定义read_text错误

1 个答案:

答案 0 :(得分:1)

您正在查看的内容不是有效的python代码,除非read_text()被定义在视线之外。函数read_text()在标准python中不存在;相反,内置函数input()可以达到这个目的。您提供的该图像的正确实现是:

def read_float(prompt):                  # prompt is a string, e.g. "Enter a float"
    while True:                          # this is to continue trying if not-a-float is entered
        try:
            number_text = input(prompt)  # this prompts the user for input, and returns a string
            result = float(number_text)  # this tries to convert the string to a float
            break                        # exit this loop to return the float
        except ValueError:               # this is thrown by the previous line if number_text isn't able to be converted to a float
            print('Enter a Number')      # ask the user to try again
    return result

在我的python控制台中运行此功能的结果:

>>> read_float("Enter a float, please: ")
Enter a float, please: float
Enter a Number
Enter a float, please: 7.5
7.5