在這個簡單的 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
原創文章,作者:ZMXLR,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/317312.html