1. 程式人生 > >Python3基礎之(二)print() 功能

Python3基礎之(二)print() 功能

一、print 字串

python 中 print 字串 要加單引號:'' 或者雙引號:""
例如:

print("hello world!")

或者:

print('hello world!')

這兩種輸出完全一樣

二、print 字串疊加

print("hello"+"world!")

輸出:

helloworld!

三、簡單運算

可以直接print 加法+,減法-,乘法*,除法/. 注意:字串不可以直接和數字相加,否則出現錯誤。
正確:

print(2+3)
print(2-3)
print(2*3)
print(2/3)

輸出:

5
-1
6
0.6666666666666666

四、int() 和 float()

當int()一個浮點型數時,int會保留整數部分,比如 int(1.9),會輸出1,而不是四捨五入。

>>> print(int(1.9))
1
>>> print(int('2')+3)
5
>>> print(float('2.6'+2))
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    print
(float('2.6'+2)) TypeError: must be str, not int >>> print(float('2.6')+2) 4.6

注意第三個語句:print(float(‘2.6’+2))
報錯的原因:字串不可以和數字直接相加