【问题标题】:Why is function not working sometimes in python?为什么函数有时在 python 中不起作用?
【发布时间】:2018-07-18 07:44:40
【问题描述】:
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() 的原始代码,但我需要知道为什么当我调用一个函数时它不起作用。

【问题讨论】:

  • 您的函数getprice() 似乎更改了一个使用变量:txt, t, it,但这些是该函数的本地变量。您的主循环使用具有这些名称的变量,但它们不是相同的变量。也许您打算退回它们。

标签: python function file variables text-files


【解决方案1】:

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

顺便说一句,it 也有同样的问题

【讨论】:

    【解决方案2】:

    我同意@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()
    

    【讨论】:

    • 嗯,返回列表并仅使用一项没有意义。 getprice() 应该有 'return tx,txt,t 并且调用站点应该是:tx,txt,t = getprice()
    • @quamrana meh,我认为返回列表还是元组并不重要。最好只返回 it 变量。
    • @juanpa.arrivillaga: 这三个都是循环使用的,所以三个都需要返回。
    • @quamrana 是的,我以为你明白了,但它确实使用了所有三个,但是如果你返回一个列表 [it, txt, t] 或一个元组 it, txt, t 真的没关系.解压一个列表和一个元组几乎是等价的。
    • @juanpa.arrivillaga:我同意返回变量,但是在调用端,它们应该如何解包?我认为解压缩tuple 更容易。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-03
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多