python從入門到進階習題(1~5)

1、打印輸出“Hello World”

#print函數實現打印輸出功能,小括號內可以是單引號也可以雙引號,結果都一樣
print('Hello World!')
print("Hello World!")

2、輸入兩個數字,並計算兩個數字之和:

num1=int(input('請輸入第一個數:'))
num2=int(input('請輸入第二個數:'))
sum=num1+num2
print('%d+%d=%d'%(num1,num2,sum))

通過輸入兩個數字來求和。使用了內置函數 input() 來獲取用戶的輸入,input() 返回一個字符串,所以我們需要使用 int() 方法將字符串轉換爲數字。兩數字運算,求和我們使用了加號 (+)運算符,除此外,還有 減號 (-), 乘號 (*), 除號 (/), 地板除 (//) 或 取餘 (%)。

3、輸入一個數字,並計算這個數字的平方根:

num = float(input('請輸入一個數字: '))
result = num ** 0.5
print(' %0.2f 的平方根爲 %0.2f'%(num ,result))

使用指數運算符 ** 來計算該數的平方根。float() 方法將字符串轉換爲浮點數類型。%.2f是保留小數點後兩位

4、用戶輸入數字,並計算二次方程:

#導入數學函數模塊
import math

a=float(input('請輸入第一個數:'))
b=float(input('請輸入第二個數:'))
c=float(input('請輸入第三個數:'))
#計算
d = (b**2) - (4*a*c)
num1 = (-b - math.sqrt(d)) / (2 * a)
num2 = (-b + math.sqrt(d)) / (2 * a)

print('結果爲 %.2f 和 %.2f'%(num1,num2))

使用了 math 模塊的 sqrt() 方法 來計算平方根。

5、輸入三角形三邊長度,並計算三角形的面積:

a = float(input('輸入第一條邊: '))
b = float(input('輸入第二條邊: '))
c = float(input('輸入第三條邊: '))

s = (a + b + c) / 2

# 計算面積
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print('三角形面積爲 %0.2f' % area)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章