當程式越打越多時,我們可以把相同的程序打包成一個函式,就像是一個數學公式,會用他的話既節省空間、時間又美觀,看起來還會很電。
def my_func(x):
for i in range(x):
print(i+1)
A = int(input("x = "))
my_func(A)
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: "Hello, Alice!"
greet("Bob") # Output: "Hello, Bob!"
def add(x, y):
return x + y
result = add(10, 20) # result is now 30
print(result) # Output: 30
def greet(name, greeting="Hello"):
print(greeting + ", " + name + "!")
greet("Alice") # Output: "Hello, Alice!"
greet("Bob", "Hi") # Output: "Hi, Bob!"
import math
1. 編寫⼀個計算圓⾯積的函數。該函數應將圓的半徑作為參數並返回⾯積。
def circle_area(radius):
return math.pi * radius**2
# Test the function
print(circle_area(2)) # Output: 12.566370614359172
print(circle_area(5)) # Output: 78.53981633974483
def factorial(num):
result = 1
for i in range(1, num+1):
result *= i
return result
# Test the function
print(factorial(5)) # Output: 120
print(factorial(10)) # Output: 3628800
def reverse_string(s):
return s[::-1]
# Test the function
print(reverse_string("hello")) # Output: "olleh"
print(reverse_string("world")) # Output: "dlrow"
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
# Test the function
print(is_prime(2))
def greet(name):
print("Hello, " + name + "!")
def add(x, y):
return x + y
# Import all functions from my_functions.py
import my_functions
my_functions.greet("Sherry") # Output: "Hello, Sherry!"
result = my_functions.add(10, 50) # result is now 60
print(result) # Output: 60
or
# Import only the greet function from my_functions.py
from my_functions import greet
greet("Sasaki") # Output: "Hello, Sasaki!"
有時候遇到套件名稱一樣的話我們很容易搞混,所以可以使用as進行改名
# Import only the greet function from my_functions.py and give it a different
name
from my_functions import greet as say_hello
say_hello("Romain") # Output: "Hello, Romain!"
我們可以在終端機下達一些指令已安裝套件或是檢查版本等等
python --version
pip install (package_name)
pip list
pip show (套件名)
pip install --upgrade package_name
pip uninstall package_name
!ls =>/content