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

问题描述 投票:-1回答:3
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()

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

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

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

python function file variables text-files
3个回答
6
投票

[txt变量是在getprice函数中定义的,不能在此函数之外使用。

顺便说一下,您在it上遇到了同样的问题


3
投票

我同意@Gelineau,您的代码应如下所示:

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])
    return it, txt, t

it = 8
while it != 1000:
    it, txt, t = 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()

0
投票

变量“ txt”超出了您调用它的位置的范围。它在函数中定义,但在while中使用(超出范围)。

© www.soinside.com 2019 - 2024. All rights reserved.