Python 程序:交换两个变量的 Python 程序


2022 年 2 月 16 日, Learn eTutorial
1522

在这个简单的 Python 程序中,我们需要使用一个临时变量来交换数字。这是一个初学者级别的 Python 程序。

要理解这个例子,您应该了解以下 Python 编程主题

如何在 Python 中交换变量?

在这个面向初学者的 Python 程序示例中,我们使用一个临时变量来交换两个变量。例如,如果 x=ay=b,然后我们进行交换,结果将是 x=by=a。这是一个使用临时变量进行交换的简单逻辑。

要在 Python 编程语言中应用此逻辑,我们必须使用一个临时变量。此临时变量用于存储 x 的值,然后我们将 y 的值赋给 x,然后将 temp 的值赋给 ytemp = x, x = y, y = temp 现在我们逐步分解代码。

算法

步骤 1:在简单的 Python 程序中使用 input 函数接受用户输入,并将该值存储到变量中。

步骤 2:创建一个临时变量 temp,并将 x 的值交换到 temp

步骤 3:将 y 的值交换到 x,然后将 temp 的值交换到 y

步骤 4:使用 format 方法在交换后打印 xy 的值。

format 方法在二次方程 Python 程序中进行了描述。

Python 源代码

                                          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('after swapping the X is: {}'.format(x))  
print('after swapping the Y is: {}'.format(y))  
                                      

输出

Enter value of x: a
Enter value of y: b


after swapping the X is: b
after swapping the y is: a