特點:需要加上引號,單雙引號都可以,包含多行內容時可以使用三引號
name = star
xxxxxxxxxx
name = "star"
print(name)
print(type(name))
name = '''長崎
良尾
'''
print(name) # 注意多行注釋與三引號多行字符串類型的區別,多行注釋的前面沒有 變量名 =
作用:生成一定格式的字符串
佔位符的三種方式:
%(較常用)
format()
格式化f
xxxxxxxxxx
name = 'cic'
print("我的名字:%s" % name)
輸出結果:
xxxxxxxxxx
我的名字:cic
%d 整數(常用)
xxxxxxxxxx
age = 18
print("我的名字:%s,年齡:%d" % (name, age))
輸出結果:
xxxxxxxxxx
我的名字:cic,年齡:18
%4d 整數(數字設置位數,不足前面補空白)
xxxxxxxxxx
a = 123
print("%6d" % a) # 不足的話原樣輸出
print("%06d" % a) # 不足的部分以0來補全
輸出結果:
xxxxxxxxxx
123
000123
%f 浮點數(常用)
xxxxxxxxxx
b = 1.2267416
print("%f" % b)
輸出結果:
xxxxxxxxxx
1.226742 # 默認後六位小數,四捨五入原則
%.4f 浮點數
數字設置小數位數
xxxxxxxxxx
print("%.3f" % b) # 多了就補0
輸出結果:
xxxxxxxxxx
1.227
%%
xxxxxxxxxx
print("我是%%的1%%" % ())
輸出結果:
xxxxxxxxxx
我是%的1%
格式:f"{表達式}"
xxxxxxxxxx
name = "cic"
age = 18
print(f"我的名字是{name},我今年{age}歲了")
輸出結果:
xxxxxxxxxx
我的名字是cic,我今年18歲了
💡 除法的商,即使是整數,也一定是浮點數
xxxxxxxxxx
print(18 / 6.3)
a = 1/1
print(type(a))
兩個斜杠//,取商的整數部分,向下取整
xxxxxxxxxx
a = 5
b = 2
print(a // b)
xxxxxxxxxx
print(a % b)
幂**
m**n,m的n次方
xxxxxxxxxx
print(a ** b)
💡 使用算數運算符,若有浮點數,結果也會有浮點數展示
xxxxxxxxxx
print(3 ** 2 + 5 / 2)
xxxxxxxxxx
num1 = 5
num2 = 10
# 將一個變量的值賦給另一個變量
xxxxxxxxxx
num3 = num1
print(num1, num2, num3)
num4 = num2
total = num2 + num4
print(total)
輸出結果:
xxxxxxxxxx
5 10 5
20
xxxxxxxxxx
a = 1
a += 1
print(a)
可以加等於,也可以減等於、乘等於、除等於、甚至幂等於
xxxxxxxxxx
m = 99
n = 66
o = m + n
m += n
print(m) # 此時m和o就是相等的
💡 賦值運算符必須連着寫,中間不能有空格,否則會報錯
💡 p += 10 # 即 p + 10 = p
但是p沒有被賦值所以不能參與運算
❗ 純數字也不能用作變量名,會報語法錯誤
xxxxxxxxxx
input(prompt)
其中的prompt是提示,會在控制台中顯示
xxxxxxxxxx
input("請輸入") # 會沒有意義,因此應該將內容賦值給一個變量
xxxxxxxxxx
name = input("請輸入姓名:")
print(name) # 不print出來的話,控制台就沒有反應
pwd = input("請輸入你的密碼:")
print(pwd)
xxxxxxxxxx
print("ry\tan")
print("姓名\t年齡\t電話")
xxxxxxxxxx
print("姓名\n年齡\n電話")
xxxxxxxxxx
print("你有\r病嗎?") # \r前面的會消失,\r在最前面就沒有變動
xxxxxxxxxx
print("q\rs") # s
print("q\\rs") # q\rs
print("q\\\\rs") # q\\rs
print(r"q\rs") # r:表示原生字符串,內容取消轉譯
輸出結果:
xxxxxxxxxx
s
q\rs
q\\rs
q\rs