您所看到的不是有效的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