搜尋此網誌

2026年8月13日星期四

Functions in Python

In Python, the return statement is used inside a function to send a value back to the caller and immediately stop the function’s execution. If no value is specified, Python automatically returns None.

def x():

    return 5

You define a function named x.

Inside the function, the return 5 statement tells Python to immediately stop running the function and send back the value 5.

Whenever you call x(), the function will give you 5.


In Python, the __code__ attribute is a special property of function objects that gives you access to the underlying code object representing the compiled function body.

def add(a, b):

    return a + b


print(add.__code__)  

# Output: <code object add at 0x..., file "script.py", line 1>


print(add.__code__.co_varnames)   # ('a', 'b')

print(add.__code__.co_argcount)   # 2

print(add.__code__.co_filename)   # "script.py"

print(add.__code__.co_name)       # "add"


backslash n
In Python, \n is the escape sequence for a newline character. It tells Python to move the cursor to the next line when printing text.

for punctuation in punctuations:
is a for loop in Python. It means: “Take each element from the list punctuations one by one, and temporarily call it punctuation.”

text = text.replace('\n', ' ')
means: “Take the string stored in text, and replace every newline character (\n) with a space (' ').”
So here, every line break is turned into a space.

def removeShortWords(text):
    return ' '.join([word for word in text.split() if len(word) > 3])
is a list comprehension filter that removes short words (length ≤ 3) from a string.
text.split() → splits the string into words (by spaces). Example: "This is a test"["This", "is", "a", "test"].
[word for word in text.split() if len(word) > 3] → keeps only words longer than 3 characters.
' '.join([...]) → joins the filtered words back into a single string with spaces.

In Python, lambda functions are small, anonymous functions defined with the lambda keyword. They’re often used when you need a quick, throwaway function without formally writing def.

In Python, sorted() is a built‑in function that returns a new sorted list from any iterable (like lists, tuples, or strings). It does not modify the original object — it creates a new one.

Iterable: a programming concept for data collections you can loop through

myList = [{'num': 3}, {'num': 2}, {'num': 1}]
sorted(myList, key=lambda x: x['num'])

The key=lambda x: x['num'] tells Python: “Sort by the value of the 'num' field inside each dictionary.”

lambda x: x['num'] is a small anonymous function that takes each dictionary (x) and returns the value associated with the key 'num'.

A dictionary in Python is a built‑in data structure that stores data as key–value pairs. Think of it like a real dictionary: the key is the word you look up, and the value is the definition you get.

Microsoft Copilot

沒有留言:

發佈留言