Homework3(作業3) <<
Previous Next >> Divisors(除數)4
Check Primality Functions (檢查功能)11
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.
(編程提供給我們的工具之一是能夠將問題分解為更簡單(或可能先前解決)或可重用的子問題。優良作法是使一個函數具有單一目的,並且該函數的名稱應以某種方式暗示其目的。大多數編程語言都具有函數,子例程或子程序的概念。)
Reusable functions(可重用功能)
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.
(如果我想每次問用戶一個數字時都想打印一個不同的字符串,但對於該函數使用相同的想法怎麼辦?換句話說,我希望函數中的變量參數在每次調用函數時都根據我(程序員)希望與眾不同的事物而改變。)
Default arguments(默認參數)
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.
(在上面的示例中,如果我不提供自定義字符串(可能占我使用此函數的時間的95%),我只想讓input()行說出來,"Give me a number: "並且省去了每次編寫此字符串的麻煩我稱這個功能。所以我能做的就是給我的函數默認參數。)
Exercise 11(練習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.).
(向用戶詢問一個數字,並確定該數字是否為質數。(對於那些忘記的人,質數是沒有除數的數。))
solution(解答)
n = int(raw_input("Enter a number to check : "))
prompt = 'Sorry negative integers are not prime !!!!!'
def isPrime(n):
# Edge case
if n<0:
return prompt
if n == 1 or n == 0:
return False
if n == 2:
return True
#primality case
for x in range(2, n):
if n%x == 0:
return False
return True
Homework3(作業3) <<
Previous Next >> Divisors(除數)4