You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python程序出现UnboundLocalError的原因及解决方案咨询

问题:UnboundLocalError: local variable 'request' referenced before assignment

作为Python新手,在Android端Pydroid运行程序时,connectionstat()函数触发UnboundLocalError: local variable 'request' referenced before assignment错误,无法明确报错原因,附上程序代码及完整运行输出:

程序代码

from datetime import datetime
from datetime import date
import requests
g = "noinput"
passhash = open("atlaspass.txt", "r")
systracer = "noinput"
var_tarih = date.today()
var_zaman = datetime.now()
#def fallbackid():
   # print("Atlas yanìt vermiyor")
def about():
           settings_about_version = open('atlasver.txt', 'r')
           settings_about_version.seek(0)     #Dosyayı baştan okur
           print("Atlas Versiyonu: " ,settings_about_version.readline())
           settings_about_codename = open('atlascodename.txt', "r")
           settings_about_codename.seek(0)
           print("Atlas ", settings_about_codename.readline())
           print()
def connectionstat():
    url = "http://google.com"
    timeout = 5
    try:
        request = request.get(url, timeout = timeout)
        print('İnternete Bağlı')
    except (requests.ConnectionError, requests.Timeout) as exception:
        print("İnternet Bağlantısı Yok")
def logon():
    tokenhash = passhash.readline()
    while True:
        atlaslogon = input("Lütfen Şifrenizi Giriniz: ")
        if atlaslogon != tokenhash:
            print('Şifre Yanlış')
        if atlaslogon == tokenhash:
            print("Şifre Doğru")
            break          
def desktop_apps():
    print("[1] - Ayarlar")
def desktop():
    print()
    print()
    print()
    print('Hoşgeldiniz')
    print()
    print()
    zaman = var_zaman.strftime("%H:%M")
    print(zaman ,  var_tarih)
    print()
    desktop_apps()
logon()
desktop()
connectionstat()

完整运行输出

Lütfen Şifrenizi Giriniz: j4debug
Şifre Doğru



Hoşgeldiniz


14:34 2022-11-15

[1] - Ayarlar
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 51, in <module>
  File "<string>", line 23, in connectionstat
UnboundLocalError: local variable 'request' referenced before assignment
[Program finished]

报错原因

核心问题是拼写错误+变量名冲突:

  • 你导入的是requests模块(注意末尾有s),但代码里误写成了request.get()(少了s);
  • 同时你把局部变量命名为request,Python会优先将request当作局部变量处理,但你在赋值request = ...之前就试图调用request.get(),相当于引用了一个未定义的局部变量,因此触发UnboundLocalError。

解决方案

  1. 修正模块调用的拼写:使用requests.get()(对应你导入的模块名);
  2. 局部变量名避免和模块名混淆,比如改成response。

修改后的connectionstat()函数代码:

def connectionstat():
    url = "http://google.com"
    timeout = 5
    try:
        # 修正拼写错误,变量名改为response避免冲突
        response = requests.get(url, timeout = timeout)
        print('İnternete Bağlı')
    except (requests.ConnectionError, requests.Timeout) as exception:
        print("İnternet Bağlantısı Yok")

内容的提问来源于stack exchange,提问作者Heisenberg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 16:25:24