用例子寫一個簡單的 Python 程序。為了演示,我們將使用算術運算符將兩個數字相加
簡單的 Python 程序相加兩個數字
這個簡單的 Python 程序相加了兩個數字,允許用戶輸入兩個值。接下來,它將把這兩個數字相加,並將總和賦給變量 sum。
number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")
# Using arithmetic + Operator to add two numbers
sum = float(number1) + float(number2)
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
Python 相加兩個數字輸出
Please Enter the First Number: 22
Please Enter the second number: 44
The sum of 22 and 44 is 66.0
在這個相加兩個數字的簡單 python 程序示例中,以下語句要求用戶輸入兩個整數,並將用戶輸入的值存儲在變量 1 和 2 中
number1 = input(" Please Enter the First Number: ")
number2 = input(" Please Enter the second number: ")
下一行,我們使用 Python 算術運算符「+」將數字 1 和數字 2 相加,然後將該總和賦給 sum。
從下面的語句中,您可以看到,我們使用 float type cast 將用戶輸入值轉換為 float。這是因為,默認情況下,用戶輸入的值是字符串類型的,如果我們在兩個字符串值之間使用+運算符,python 會連接這兩個值,而不是相加它們
sum = float(number1) + float(number2)
下面的 Python 打印語句將輸出 sum 變量(22 + 44 = 66)。
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
這個 python 程序在加兩個正整數的時候加兩個數字效果很好,加正負整數怎麼樣?讓我們看看
相加兩個數字的示例 Python 程序示例 2
負數也沒問題!。編寫上述 python 相加兩個數字程序的替代方法是:
number1 = float(input(" Please Enter the First Number: "))
number2 = float(input(" Please Enter the second number: "))
# Using arithmetic + Operator to add two numbers
sum = number1 + number2
print('The sum of {0} and {1} is {2}'.format(number1, number2, sum))
Please Enter the First Number: 25
Please Enter the second number: 91
The sum of 25.0 and 91.0 is 116.0
注:以上簡單的程序將限制用戶,不輸入字符串值作為輸入
原創文章,作者:VREBW,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/130663.html