【问题标题】:how to swap two variables in python?如何在python中交换两个变量?
【发布时间】:2023-02-04 13:52:46
【问题描述】:

代码太简单了,我知道这段代码可以正常工作

# Python program to swap two variables

x = 5
y = 10

# To take inputs from the user
#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values
temp = x
x = y
y = temp

print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}'.format(y))

我想要任何其他方法来执行此操作,是否有任何标准方法可以执行此操作,如果是,请告诉我。

【问题讨论】:

标签: python variables syntax swap


【解决方案1】:

是的,有一种使用元组解包在 Python 中交换两个变量的标准方法:

x, y = y, x

这行代码将在不使用临时变量的情况下交换 x 和 y 的值。

【讨论】:

    【解决方案2】:
    a= 5
    b = 6
       
    a = b, b = a
    
    print("value of a after swap: ", format(a))
    print("value of b after swap: ", format(b))
    

    【讨论】:

      【解决方案3】:
      x = int(input("enter the value of x:"))
      y = int(input("enter the value of y:"))
      print("before swapping")
      print(x)
      print(y)
      
      x, y = y, x
      print("after swapping")
      print(x)
      print(y)
      

      【讨论】:

        猜你喜欢
        • 2013-04-18
        • 2017-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-02
        • 1970-01-01
        • 2018-07-20
        相关资源
        最近更新 更多