10:List Overlap Comprehensions 列表重疊理解 <<
Previous Next >> 12:List Ends 清單結尾
11:Check Primality Functions 檢查基本功能
Exercise 11 (and Solution) 練習11(和解決方案)
Ask the user for a number and determine whether the number is prime or not. (For those who have forgotten, a prime number is a number that has no divisors.). You can (and should!) use your answer to Exercise 4 to help you. Take this opportunity to practice using functions, described below.
向用戶詢問一個數字,並確定該數字是否為質數。 (對於那些忘記的人,質數是沒有除數的數。) 您可以(並且應該!)使用練習4的答案來幫助您。 藉此機會練習使用如下所述的功能。
Discussion 討論區
Concepts for this week 本週的概念:
• Functions 職能
• Reusable functions 可重用功能
• Default arguments 默認參數
Functions 職能
One of the tools programming gives us is the ability to break down problems into easier (or perhaps previously solved) or reusable subproblems. It is good practice to have a function have a single purpose, and the name of that function should hint at it’s purpose in some way.
編程提供給我們的工具之一是能夠將問題分解為更簡單(或可能先前解決)或可重用的子問題。 優良作法是讓一個功能具有單一目的,並且該功能的名稱應以某種方式暗示其目的。
Most programming languages have this idea of a function, subroutine, or subprogram. In Python, a function is a programming construct that allows exactly that.
大多數編程語言都具有函數,子例程或子程序的概念。 在Python中,函數是一種允許這樣做的編程構造。
Let’s look at a simple example
讓我們看一個簡單的例子:
def get_integer(): return int(input("Give me a number: "))
In this small example, we used the same code that asks a user for input as a tabbed line underneath this def statement. The def means that everything tabbed underneath is a function. The name get_integer() is just a name that I (the programmer) made up. If I just include this code inside a Python file and run it, nothing will happen - all I have done so far is wrapped my code inside of a function; I never told my program to actually RUN my function.
在這個小示例中,我們使用了相同的代碼,要求用戶在此def語句下方輸入為選項卡行。 def表示位於其下的所有選項卡都是一個函數。 名稱get_integer()只是我(程序員)組成的名稱。 如果我只是將此代碼包含在Python文件中並運行它,則將不會發生任何事情-到目前為止,我所做的一切都將我的代碼包裝在一個函數中; 我從未告訴過我的程序實際運行我的功能。
def get_integer():
return int(input("Give me a number: "))
age = get_integer()
school_year = get_integer()
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
What I have done here is called the function (told it to run) by writing age = get_integer()
. When this line of code runs, what happens is the program will execute (run) the function by asking me for a number, then returning it (giving it back to me) by saving it inside the variable age
. Now when I want to ask the user for another number (this time representing the school year), I do the same thing with the variable school_year
.
通過寫age = get_integer(),我在這裡所做的被稱為函數(告訴它運行)。 當這行代碼運行時,程序將通過詢問我的數字來執行(運行)該函數,然後將其保存在變量age中以將其返回(交還給我)。 現在,當我想問用戶另一個數字(這次代表學年)時,我對變量school_year做同樣的事情。
Reusable functions 可重用功能
This is all well and good, but I can make my function do much more for me. Right now, my function will always ask the user for a number by printing the string "Give me a number: ". What if I want to print a different string every time I ask the user for a number, but otherwise use the same idea for the function? In other words, I want a variable parameter in my function that changes every time I call the function based on something I (the programmer) want to be different.
這一切都很好,但是我可以讓我的功能為我做更多的事情。 現在,我的函數將始終通過打印字符串“給我一個數字:”來要求用戶輸入數字。 如果每次我問用戶一個數字時都想打印一個不同的字符串,但對於該函數使用相同的想法怎麼辦? 換句話說,我希望函數中的變量參數在每次調用函數時都根據我(程序員)希望與眾不同的事物而改變。
I can do this by passing (giving) my function a variable. Like this
我可以通過傳遞(給我的)函數一個變量來做到這一點。 像這樣:
def get_integer(help_text):
return int(input(help_text))
Now what I can do when I call the function is something like this:
def get_integer(help_text):
return int(input(help_text))
age = get_integer("Tell me your age: ")
school_year = get_integer("What grade are you in? ")
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
Now it is easier for a user to use the program, because the help text is different.
These variables you pass to functions are called variables, parameters, or arguments.
現在,由於幫助文本不同,因此使用戶更容易使用該程序。
傳遞給函數的這些變量稱為變量,參數或參數。
Default arguments 默認參數
In the example above, once I have added an argument to my function, I always have to give an argument when I call the function. I can’t forget to give the get_integer() function from above a string to print to the screen. In some cases, I want there to be a “default” behavior for my function that happens when I create an argument for it but don’t give it any.
在上面的示例中,在向函數添加參數後,在調用函數時始終必須提供參數。 我不能忘記從字符串上方給get_integer()函數打印到屏幕上。 在某些情況下,我希望函數有一個“默認”行為,這種行為會在我為其創建參數但不提供任何參數時發生。
In the example above, if I don’t give a custom string (which may be 95% of the time I use this function), I just want the input()
line to say "Give me a number: "
and I want to save myself the trouble of writing this every single time I call the function. So what I can do is give my function default arguments. Like so:
在上面的示例中,如果我不提供自定義字符串(使用該函數的時間可能是95%),我只想讓input()行說“給我一個數字:”,而我想 節省了我每次調用該函數時編寫此代碼的麻煩。 所以我能做的就是給我的函數提供默認參數。 像這樣:
def get_integer(help_text="Give me a number: "):
return int(input(help_text))
What happens now is I can use the function in two ways: by giving it an argument and by NOT giving it an argument.
現在發生的事情是我可以通過兩種方式使用該函數:通過給它一個參數和不給它一個參數。
def get_integer(help_text="Give me a number: "): return int(input(help_text)) age = get_integer("Tell me your age: ") school_year = get_integer() if age > 15: print("You are over the age of 15") print("You are in grade " + str(school_year))
The first time I call the function, it will print "Tell me your age: "
, but the second time, it will print "Give me a number: "
, because I did not give it a string and it will execute the default behavior.
第一次調用該函數時,它將打印“告訴我您的年齡:”,但是第二次它將顯示“給我一個數字:”,因為我沒有給它提供字符串,它將執行默認行為 。
Recap 回顧
What a function does is wrap a piece of code that we want to reuse, labels it, and allows us to use it again relatively easily. You can add variables to the functions to make your code even MORE reusable, and you can add default arguments to these variables.
Functions are a bit strange to deal with at first, but once you master them, they will be your savior in programming. Besides, the whole point of learning programming is abstraction, problem solving, breaking down problems, and that’s exactly what functions are all about.
函數的作用是包裝我們要重用的一段代碼,對其進行標記,並允許我們相對容易地再次使用它。 您可以將變量添加到函數中,以使代碼更加可重用,並且可以將默認參數添加到這些變量中。
一開始處理函數有點奇怪,但是一旦掌握了這些函數,它們就會成為您編程中的救星。 此外,學習編程的重點是抽象,解決問題,解決問題,而這正是功能的全部內容。
Happy coding! 祝您編碼愉快!
10:List Overlap Comprehensions 列表重疊理解 <<
Previous Next >> 12:List Ends 清單結尾