首页 > 编程知识 正文

Python 程序:交换两个变量

时间:2023-11-25 09:12:55 阅读:309056 作者:NPDU

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

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

  • Python 语法
  • Python 数据类型
  • Python 安装和设置

如何在 python 中交换变量?

这里的这个 python 程序的例子是给初学者的;我们用一个临时变量来交换两个变量。例如:如果 x=a 和 y=b 那么我们做互换,结果就是 x=b 和 y=a 。这是一个使用临时变量进行交换的简单逻辑。

为了在 python 编程语言中应用这个逻辑,我们必须使用一个临时变量。这个临时变量用来存储 x 的值,我们把 y 的值应用到 x 上,然后把 temp 的值应用到 y 上 temp = x,x = y,y = temp 现在我们一步一步的破解代码。

算法

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

第二步:创建一个临时变量 temp ,并将 x 的值换成 temp 。

第三步:将 y 的值换成 x ,然后将温度的值换成 y 。

第四步:用格式化的方法打印交换后的 x 和 y 的值。

格式方法在二次方程 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 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。