Py学习  »  Python

在python中读取文本的用途和目的

Ahmed Sheikh • 5 年前 • 1519 次点击  

这是密码

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

但我收到的输入终端读取文本的错误没有定义

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/42923
 
1519 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Green Cloak Guy
Reply   •   1 楼
Green Cloak Guy    6 年前

您所看到的不是有效的python代码,除非 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