为什么函数有时在python中不起作用?

Sap*_*aka -1 python variables file function text-files

import time

def taym():
    time.sleep(5)

def getprice():
    myfile = open('C:\\Users\\DELL\\Desktop\\Python\\html1.html')
    txt = myfile.read()
    t = txt.find("$")
    it = float(txt[t-4:t])

it=8
while it != 1000:
    getprice()
    if it <= 4.74:
        print("Price is Ok!")
        taym()
    else: 
        print("The price of the coffee beans is "+txt[t-4:t+1])
        taym()
Run Code Online (Sandbox Code Playgroud)

当我在python3中运行此代码时,我收到如下错误消息:

"print("The price of the coffee beans is "+txt[t-4:t+1])
NameError: name 'txt' is not defined."
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用getprice()循环内部的原始代码,但是当我有一个我调用的函数时,我需要知道为什么它不起作用.

Gel*_*eau 6

变量txt是在getprice函数中定义的,你不能在这个函数之外使用它.

it顺便提一句,你遇到了同样的问题