Python 以下哪一个是正确的语法?

Python 以下哪一个是正确的语法?,python,syntax,Python,Syntax,初学者程序员在这里。我正在制作一个简单的程序来显示我的计算机本地IP地址和网络的外部IP地址。这真的不是一个问题,但更多的只是一个问题 那么,这些格式中哪一种是首选语法 一, 二, 提前谢谢。我想说第一个。它的优点是总是返回字符串,如果不返回,则抛出异常。这是一种可以预测和理解的行为。这意味着更容易编写文档,而且无法访问您的源代码的人可以理解并使用FetchExternalAddress()方法 只要您正确地记录您的方法,表明它返回一个字符串,并在未检测到有效的Internet连接时抛出异常 你

初学者程序员在这里。我正在制作一个简单的程序来显示我的计算机本地IP地址和网络的外部IP地址。这真的不是一个问题,但更多的只是一个问题

那么,这些格式中哪一种是首选语法

一,

二,


提前谢谢。

我想说第一个。它的优点是总是返回
字符串
,如果不返回,则抛出异常。这是一种可以预测和理解的行为。这意味着更容易编写文档,而且无法访问您的源代码的人可以理解并使用
FetchExternalAddress()
方法

只要您正确地记录您的方法,表明它返回一个
字符串
,并在未检测到有效的Internet连接时抛出
异常


你也应该避免在你的方法中出现副作用,比如你的
打印(“没有互联网连接”)
,因为它可能会给用户带来意想不到的打印效果。

我想说的是第一个。它的优点是总是返回
字符串
,如果不返回,则抛出异常。这是一种可以预测和理解的行为。这意味着更容易编写文档,而且无法访问您的源代码的人可以理解并使用
FetchExternalAddress()
方法

只要您正确地记录您的方法,表明它返回一个
字符串
,并在未检测到有效的Internet连接时抛出
异常

您还应该避免在方法中出现诸如
打印(“无互联网连接”)
之类的副作用,因为这可能会导致用户意外打印

# -*- coding: utf-8 -*-

from socket import gethostname, gethostbyname
from requests import get
from requests.exceptions import ConnectionError

def FetchLocalAddress():
    hostname = gethostname()
    ip = gethostbyname(hostname)
    return ip

def FetchExternalAddress():
    ip = get('https://api.ipify.org').text
    return ip

try:
    print('Local ip-address: {}'.format(str(FetchLocalAddress())))
    print('External ip-address: {}'.format(str(FetchExternalAddress())))
except ConnectionError:
    print('No internet connection.')
# -*- coding: utf-8 -*-

from socket import gethostname, gethostbyname
from requests import get
from requests.exceptions import ConnectionError

def FetchLocalAddress():
    hostname = gethostname()
    ip = gethostbyname(hostname)
    return ip

def FetchExternalAddress():
    try:
        ip = get('https://api.ipify.org').text
        return ip
    except ConnectionError:
        print('No internet connection.')

print('Local ip-address: {}'.format(str(FetchLocalAddress())))
external = FetchExternalAddress()
if external is not None:
    print('External ip-address: {}'.format(str(external)))