Python基礎 輸入輸出

2021-09-13 11:52:34 字數 1818 閱讀 2584

基本格式

常用格式化字元

含義%s

字串%d

有符號十進位制的整數,%06d 輸出的整數顯示位數,不足的地方使用0補全

%f浮點數%.2f表示顯示小數點的後兩位

%%輸出%

變數輸出例項

需求:定義整數變數 student_no,輸出 我的學號是 000001

student_no = 1

print ( "學號是%06d" % student_no)

# %06d對整數進行站位,當不足6位的時候會進行補操作

需求:定義小數 price、weight、total_price,輸出蘋果單價 9.00 元/斤,購買了5.00 斤,需要支付 45.00 元

price = 6.5

weight = 3.5

total_price = price * weight

print( " 總價為 : %.2f " % total_price )

# %f是對於浮點小數進行站位,%.2f是對小數點保留後兩位

# 如果需要對多個資料進行站位,需要把真實資料括號包裹,並以逗號分隔

"""定義小數 price、weight、total_price,輸出 蘋果單價 9.00 元/斤,購買了 5.00 斤,需要支付 45.00 元"""

print( "蘋果單價: %.2f 元/斤,重量:%.2f 斤,總價:%.2f元" % (price,weight,total_price))

# %s 可以對任意型別進行站位,包含字串.%5s表示站位5個字元空間

print( "蘋果單價: %5s元/斤,重量: %s斤,總價: %5s元" % (price,weight,total_price))

變數輸入例項
目前暫時只有兩個函式printtype

變數(被當做字串)  = input(對應資訊)
型別轉換函式

函式說明

int(x)

將x轉化為整型

float(x)

將x轉化為浮點型

浮點型的字串無法轉換為int,比如int(1.5)會出現報錯

變數型別的例項

需求:計算隨機金額的總價並保留精度

# content = input( "請輸入內容:")

# print( "輸入的內容為:%s" % content)

# print( type( content ))

# # 返回是乙個字串的型別

price_str = input( "單價:")

weight_str = input( "重量:")

#以上內容全部都是字串型別不能直接計算,需要單獨轉化型別

price = float( price_str)

weight = float( weight_str)

total_price = price * weight

print( "總價:%5s" % total_price )

# round (資料 , 保留位數) 保留指定的位數,進行四捨五入,解決浮點運算精度缺失問題

total_price = round( price * weight , 4)

print( total_price)

python基礎 輸入輸出

input print 知識點 1.input預設接收使用者輸入內容為字串型別 2.print直接輸出字串內容 card id input 請輸入學號 pwd input 請輸入密碼 print card id print type card id print pwd 1.print列印字串 pri...

python基礎輸入輸出

輸出 print 加上 字串就可以輸出 print 函式也可以接受多個字串,用逗號 隔開,結果 會變成空格 print 函式中可以直接進行簡單的數 算 print 字串 輸出變數 表示拼接 兩邊的變數型別必須保持一致 格式化輸出 print 字串 s,s,s 對應佔位符的內容 s佔位符 str強制轉...

Python基礎 輸入輸出

輸出 print 如果要在一行中輸出多個值,那麼輸出的n個值分別使用逗號隔開 例如 print val1,val2 輸入 raw input some description python 2.7語法 input some description python 3.x語法 輸入密碼 先導入getpa...