k2

360全家通發表於2024-10-22

計算導論

字典序

  • python內建字典序比較

縮寫

a+=b 意思是a=a+b
同理-= /= %= *= //=

str字串計算

str1="HE"
str2="S"
a=str12
print(str1+str2,a,str1
3+str2*2)

HES HEHE HEHEHESS

eval

把字串的值進行計算

sum = eval(1+2/3)
print(sum)#即為所得結果輸出為整數或者浮點數

1.6666667

int

a=int(133.77)
b=int(float("12.34")
c=int("12")
print(a,b,c)

133 12 12

input

x=int(input("輸入數字")) 12
y=input(輸入) 12
z=int(float(input("輸入"))) 13.5
print(x,y,z,type(y))

12 12 13.5 str

print

age=1
city="bs"
print("a"+str(age)+"b")
print("a %d b c %s"%(age,city))#%d指整數 %f指浮點數 %s指字串 從左往右對應每一個值
print("a{}b{}".format(age,city)) #"{}"為佔位符直接把值放上去
print(f"a{age}b{city}")

a 1 b
a 1 b c bs
a 1 b bs
a 1 b bs

在print裡面表示大括號要用兩個來表示
math.a

大括號

num = "{}".format(2*37)
print(num, type(num))
74 <class 'str'>

大括號中的保留小數位數
print(f'The value of pi is approximately {math.pi:.10f}.') 直接在裡面引用的要在前面加f
print('The value of pi is approximately {:.10f}.'.format(math.pi))

The value of pi is approximately 3.1415926536.

多重大括號

exp1 = f"{70 + 4}"
exp2 = f"{{70 + 4}}"
exp3 = f"{{{70 + 4}}}"
exp4= f"{{{{70 + 4}}}}"
print(exp1, exp2, exp3, exp4)

74 {70 + 4} {74} {{70 + 4}}

str1 ="Hello World."
str2 ="Shanghai Jiao Tong University"
str3 ="苟利國家生死以,豈因禍福避趨之?"

print(str1, end=' ')
print(str2, end='!! ')
print(str3, end=' ')
print()

print(str1, end="$\n")
print(str2, end="$\n")
print(str3, end="$\n")

print(str1, end= ">.<\n")
print(str2, end= ">. <\n")
print(str3, end= ">.<\n")

exp1 = f"{70 + 4}"
exp2 = f"{{70 + 4}}"
exp3 = f"{{{70 + 4}}}"
exp4= f"{{{{70 + 4}}}}"

print(exp1, exp2, exp3, exp4, sep=" | ")

Hello World. Shanghai Jiao Tong University!! 苟利國家生死以,豈因禍福避趨之?
Hello World.$
Shanghai Jiao Tong University$
苟利國家生死以,豈因禍福避趨之?$
Hello World.>.<
Shanghai Jiao Tong University>. <
苟利國家生死以,豈因禍福避趨之?>.<
74 | {70 + 4} | {74} | {{70 + 4}}

定義

str1="H"

def my_print(msg):
print("1", end=" ")#end等於空格換行
print(msg, end=" ")
print("1")
my_print(str1)#將str1代入變元msg執行myprint函式

return返回變元