在Python中使用return

2024-04-19 19:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是能够在相应的位置使用x 如果回复是1,那么位置1中的x应该是1,但是如果我使用这个代码,那么x直到该位置被执行之后才会返回。但是,如果先执行return命令,则由于return完成了功能,因此不会执行位置。你知道吗

def town():
    reply = input('What is your rely?')

    if reply == '1':
        x = 1
        location1()
        return x

    if reply == '2':
        x = 2 
        location2()
        return x

    if reply == '3':
        x = 3 
        location3()
        return x

有人能给我一个解决方案吗?越简单越好。 谢谢


Tags: 代码命令功能目标inputyourreturnif
2条回答

问题不在于回报,而在于你没有使用论据。可以使用location(x)将x传递给location方法。不用再回来了。你知道吗

def town():
    reply = input('What is your rely?')
    if reply == '1':
        location1(reply)
    elif reply == '2':
        location2(reply)
    elif reply == '2':
        location3(reply)

def location1(argument):
   print("reply was " + argument)

def location2(x):
   print("reply was " + x)

def location3(argument):
   print("reply was " + argument)

还有一点代码效率:在town()上,我们将参数reply传递给location()方法,因为我们已经检查了它是“1”、“2”还是“3”(根据您的if)。无需使用名为x的新变量,并在当前reply已具有该值时为其赋值。你知道吗

我可以向您建议以下解决方案,并提供一些意见供您理解:

def town():
    reply = input('What is your reply? ')

    if reply in '123':
        # Here: the reply is '1', '2' or '3'
        x = int(reply)  # it converts the string into an integer
        location(x)     # it passes the integer as parameter to the function 'location'
        return x        # it returns the integer value
    else:
        # Here: the reply is different from '1', '2' or '3'
        print("Reply is different from '1', '2' or '3'")
        return None

def location(x):
    # Do something depending on the value of the input parameter x
    if x == 1:
        do_something_1()  # Implement what you want here
    elif x == 2:
        do_something_2()  # Implement what you want here
    else:
        do_something_3()  # Implement what you want here

town()

相关问题 更多 >