V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
smallgoogle
V2EX  ›  Python

Python 变量赋值 没有成功,偶发性现象 诡异

  •  
  •   smallgoogle · 2020-04-21 16:32:01 +08:00 · 1223 次点击
    这是一个创建于 1468 天前的主题,其中的信息可能已经有所发展或是发生改变。

    原始代码:

    def get_http_ip():
        res = requests.get('http://www.xxx.com')
        res = json.loads(res.text)
        if res['code'] == 200:
            print(res['data'])    # 这里打印结果都还是正常的
            time.sleep(5)    # 我猜有可能有人说太快了,那么我这里给一个定时器。
            # 我猜,肯定有人说你在这写一个变量先赋值一下,然后再把变量返回出去
            # 我当然试过了,结果依然是一样的,一样会出现 None
            return res['data']
        else:
            time.sleep(1)
            get_http_ip()
    
    
    def start():
        info = get_http_ip()
        print(info)    # 这个位置有些时候会打印出 None,这是为啥呢?
    
    
    if __name__ == '__main__':
        start()
    
    
    

    修正的代码:

    ip_list = ''
    
    def get_http_ip():
        global ip_list
        res = requests.get('http://www.xxx.com')
        res = json.loads(res.text)
        if res['code'] == 200:
            ip_list = res['data']    # 我把结果赋值给全局变量
            return res['data']
        else:
            time.sleep(1)
            get_http_ip()
    
    
    def start():
        global ip_list
        info = get_http_ip()
        if info == None:    # 我这里写一个判断如果返回 None 我就用全局变量赋值
            info = ip_list
        print(info)
    
    
    if __name__ == '__main__':
        start()
    
    
    

    那么问题来了,为啥我第一个办法有些时候会返回 None 呢?
    我瞎猜,是不是内存指针跟不上?
    就是前辈们指教一下,什么原因导致的?

    jyyx
        1
    jyyx  
       2020-04-21 16:34:50 +08:00
    递归那里没有返回, else 里面没有 return
    改成 return get_http_ip()
    Virace
        2
    Virace  
       2020-04-21 16:38:24 +08:00 via Android
    马虎
    wzwwzw
        3
    wzwwzw  
       2020-04-21 16:39:46 +08:00
    递归哪里修改成 return get_http_ip()
    smallgoogle
        4
    smallgoogle  
    OP
       2020-04-21 16:41:38 +08:00
    @jyyx @Virace @wzwwzw 沉了 沉了。对不起。对不起。占用资源了。哎。。。
    littleylv
        5
    littleylv  
       2020-04-21 16:42:38 +08:00
    递归,了解一下递归
    答案楼上已经说了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1664 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:47 · PVG 00:47 · LAX 09:47 · JFK 12:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.