#save name to names list
names = []
for _ in range(3):
names.append(input("What's your name? "))
for name in sorted(names):
print(f"hello, {name}")
$python names.py
What's your name? Ted
What's your name? Harry
What's your name? Rone
hello, Harry
hello, Rone
hello, Ted
names.py
names.py
# Writes to a new file
name = input("What's your name? ")
file = open("names.txt", "w")
file.write(name)
file.close()
$ python names.py
What's your name? Ted
$ cat names.txt
Ted
names.py
# Writes to a new file
name = input("What's your name? ")
file = open("names.txt", "a")
file.write(f"{name}\n")
file.close()
$ python names.py
What's your name? Ted
$ python names.py
What's your name? Harry
$ cat names.txt
Ted
Harry
# Adds context manager
name = input("What's your name? ")
with open("names.txt", "a") as file:
file.write(f"{name}\n")
$ python names.py
What's your name? Ted
$ python names.py
What's your name? Harry
$ cat names.txt
Ted
Harry
names.py
# Reads from a file
with open("names.txt") as file:
lines = file.readlines()
for line in lines:
print("hello,", line.rstrip())
$ python names.py
hello, Ted
hello, Harry
$ cat names.txt
Ted
Harry
names.py
# Reads from a file, one line at a time
with open("names.txt") as file:
for line in file:
print("hello,", line.rstrip())
$ python names.py
hello, Ted
hello, Harry
$ cat names.txt
Ted
Harry
names.py
逗點分格資料的純文字檔案檔案格式
$ code students.csv
張三,123456
李四,135793
王五,243666
# Reads a CSV file
with open("students.csv") as file:
for line in file:
row = line.rstrip().split(",")
print(f"{row[0]} number is {row[1]}")
$ python names.py
張三 number is 123456
李四 number is 135793
王五 number is 243666
names.py
# Unpacks a list
with open("students.csv") as file:
for line in file:
name, number = line.rstrip().split(",")
print(f"{name} number is {number}")
$ python names.py
張三 number is 123456
李四 number is 135793
王五 number is 243666
names.py
匿名函式,不需要定義名稱,只有一行運算式
lambda parameter_list: expression
lambda : 關鍵字
parameter_list : 參數清單
expression : 運算式
def square(x):
return x ** 2
square = lambda x: x ** 2
square(2)
4
def add(x,y):
return x + y
add = lambda x, y: x + y
print(add(1, 2))
print(add(3, 5))
print(add)
3
8
<function <lambda> at 0x7fada83b1f28>
def abs_number(x):
if x >= 0:
return x
else:
return -x
abs_number = lambda x : x if x >= 0 else -x
print(abs_number(10))
print(abs_number(-2))
10
2