python简单笔记
Remarks:python中注意縮進(Tab鍵或者4個空格)
print(輸出)
格式:print(values)
字符串、數字、變量等都可以輸出: 實例: print(1)->1 print(1+1)->2 a = "hello" print(a)->hello print(f"a的值是{a}")->a的值是hello多行輸出:
print("""aaaaaaaaaaaa aaaaaaaaa aaaaaaaaaa""")結果:
aaaaaaaaaaaa aaaaaaaaa aaaaaaaaaa說明括號中 f 和 {變量} 配合可提取字符串中的變量,同print("a的值是",a)效果一樣
f 和 {變量} 也可在變量中使用
換行輸出
實例:
>>> print("ABC\nDEF") ABC DEF不換行輸出
格式:end=‘’
實例:
執行結果:
ABCDEF變量
變量
格式:變量名稱 = values
實例:
one = 1 two = 2 three = one + two print(three)輸出結果:
3全局變量
全局可使用
你可以這樣寫:
執行結果:
1314520也可以這樣寫使用 global 關鍵字:
def fun():global varvar = 1314print(var, end='')fun() print(var)執行結果:
13141314一般多用在函數內,聲明變量的作用域為全局作用域。
下面是一個錯誤的示例:
def fun():var = 1314print(var, end='')fun() print(var) # 這一步就會報錯因為var為函數中的局部變量,外面根本沒用var這個變量注意: 盡量不要使用全局變量,會導致代碼可讀性變差,代碼安全性降低
格式化
format
格式 {位置0}{位置1}.format(參數a,參數b)
注意:format前面有個點.
執行結果:
1 2 3 4 one two three four True False False True 1 2 3 4 Try your Own text here Maybe a poem Or a song about fear%d、%s、%f
%d:有符號整數(十進制)
%s :字符串形式
%f:小數
實例:
更多格式化詳解
接收用戶輸入
格式:變量 = input()
實例1:
print("How old are you?", end=' ') age = input() print("How tall are you?", end=' ') height = input() print("How much do you weigh?", end=' ') weight = input() print(f"So, you're {age} old, {height} tall and {weight} heavy")結果:
How old are you? 18 How tall are you? 180 How much do you weigh? 100 So, you're 18 old, 180 tall and 100 heavy實例2:
print("請輸入你的年齡:",end='') a = int(input()) #執行到這會等待用戶輸入 print(f"你的輸入的年齡是{a}")結果:
請輸入你的年齡:18 #執行到這會等待用戶輸入 你的輸入的年齡是18實例3:
age = int(input("How old are you? ")) height = input("How tall are you? ") weight = input("How much do you weigh? ") print(f"So, you're {age} old, {height} tall and {weight} heavy")結果:
How old are you? 18 How tall are you? 180 How much do you weigh? 50 So, you're 18 old, 180 tall and 50 heavy模塊導入
from sys import argv #argv獲取當前腳本路徑 # read the WYSS section for how to run this print(argv) script = argv print("The script is called:", script)執行結果:
['D:/xuexi/python練習.py'] The script is called: ['D:/xuexi/python練習.py']讀取文件
格式:open()
實例:
shiyan.txt 的內容是:
執行結果:
如果沒有 a.txt 和 a.txt 會自動在結果路徑中創建
a.txt --> 小a:我是小a
b.txt --> 小b:我是小b
文件打開方式:
模式 可做操作 若文件不存在 是否覆蓋 r 只能讀 報錯 - r+ 可讀可寫 報錯 是 w 只能寫 創建 是 w+ 可讀可寫 創建 是 a 只能寫 創建 否,追加寫 a+ 可讀可寫 創建 否,追加寫函數
格式:
def functionname():
一個簡單的函數
def test():print("This is one function")a = 1b = 2print(a + b)test() #調用函數結果:
This is one function 3可傳參的函數
def test(a,b):print("This is one function")print(a + b)test(1,2) #調用函數結果:
This is one function 3帶默認值的
def test(a,b=2):print("This is one function")print(a + b)test(1) #調用函數結果:
This is one function 3設置默認值后也可以傳新值:
def test(a,b=2):print(f"This is one function")print(a + b)test(1,3) #調用函數結果:
This is one function 4注意: 默認參數只能在非默認參數之后(下面將演示一段錯誤的代碼):
def function(a,b=1,c,d=2): #這樣寫是錯誤的,因為非默認參數c不應該出現在b之后,應該在b之前簡單命令,未完結
轉載于:https://www.cnblogs.com/weibgg/p/10787078.html
總結
以上是生活随笔為你收集整理的python简单笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SG函数
- 下一篇: HALCON示例程序hull.hdev区