如何在Python中摆脱None [英] How to get rid of None in Python

查看:100
本文介绍了如何在Python中摆脱None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import sys
import socket
import time
ip=([(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])


x="........"

def print_word_slowly(word):
    for i in word:
        sys.stdout.write(i)
        sys.stdout.flush()
        time.sleep(0.2)
        
        
        
print "Loading...\n"
print print_word_slowly("obtaining IP address......."), "     \nIP Address obtained. IP Address is %s."%(ip)







打印出:




This prints out:

Loading...                                                                                                                               
                                                                                                                                         
obtaining IP address.......None                                                                                                          
IP Address obtained. IP Address is 172.17.29.xxx.



如何在获取IP地址后摆脱'无'.......


How can I get rid of 'None' after 'obtaining IP address.....'?

推荐答案

问题是Python函数的隐藏返回值。如果函数不包含 return 语句,那么它会自动添加一个,并返回值,如 https://docs.python.org/3.3/reference/simple_stmts.html#index-21 [ ^ ]。所以你的 print 语句调用该函数,该函数打印消息,然后得到返回值并打印出来,在打印其余参数之前。
The issue is down to the hidden return value from a Python function. If a function does not include a return statement, then it automatically adds one, and returns the value None, as described in https://docs.python.org/3.3/reference/simple_stmts.html#index-21[^]. So your print statement calls the function, which prints the message, then gets the return value of None and prints that, before printing the remainder of its parameters.


你应该删除print_word_slowly()函数之前的第一个打印。

尝试直接调用你的函数而不是打印它。
You should delete the first "Print" before your "print_word_slowly() function".
Try call your function directly rather than "Print" it.


这篇关于如何在Python中摆脱None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆