使用函数对int变量进行排序

时间:2017-03-20 00:00:18

标签: python

我想使用python函数将3个int排序为升序。我试了几下,但我不确定我做错了什么。

s = int(input())
m = int(input())
l = int(input())
temp = 0
def sortasc(x,y):
    if x > y:
        temp = y
        y = x
        x = temp
sortasc(s,m)
sortasc(m,l)
sortasc(s,m)
print(s,m,l)

1 个答案:

答案 0 :(得分:0)

您的参数变量在函数中被修改,但这不会反映到查看全局变量且无法访问函数局部变量的调用者。

解决此问题的一种方法是让函数返回正确的值(按正确的顺序):

s = int(input())
m = int(input())
l = int(input())

def sortasc(x,y):
    if x > y:
        return y,x
    return x,y

s,m = sortasc(s,m)
m,l = sortasc(m,l)
s,m = sortasc(s,m)
print(s,m,l)

repl.it

上测试

或者,您可以通过列表将引用传递给这两个值:

s = int(input())
m = int(input())
l = int(input())

def sortasc(lst, i, j):
    if lst[i] > lst[j]:
        lst[i], lst[j] = lst[j], lst[i]

lst = [s, m, l]
sortasc(lst, 0, 1)
sortasc(lst, 1, 2)
sortasc(lst, 0, 1)
print(lst[0], lst[1], lst[2])

repl.it

上查看它