A. raw_input
返回值的數據類型是string
,所以需要類型轉換
>>> item = raw_input("Enter Number:")
Enter Number:2
>>> type(item)
<type 'str'>
>>> item = int(raw_input("Enter Number:"))
Enter Number:4
>>> type(item)
<type 'int'>
>>>
B.類型轉換期間的異常處理:如果用戶從數字中輸入任何其他字符,則上面的代碼將引發需要處理的異常。
例如
>>> item = int(raw_input("Enter Number:"))
Enter Number:w
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'w'
演示使用異常處理:
>>> try:
... item = int(raw_input("Enter Number:"))
... except ValueError:
... print "Enter only digits."
...
Enter Number:rt
Enter only digits.
C. 與實際算法
一個。不需要count
變量邏輯。
b。在返回值期間不需要if
循環。
c。最好將功能號碼更改爲sumOfOddNumbers
即更有意義。
演示:
def sumOfOddNumbers (numbers_list):
total = 0
for number in numbers_list:
if (number % 2 == 1):
total += number
return total
D.使用list comprehension,sum方法,lambda功能在其他的答案
提及
E. 時間運行以下代碼:
lst = range(10000000)
def sum_of_odd_numbers1():
return sum((i*(i%2) for i in lst), 0)
def sum_of_odd_numbers2():
return sum((i for i in lst if i%2), 0)
def sum_of_odd_numbers3():
return sum(filter(lambda x: x%2, lst), 0)
def sumOfOddNumbers():
total = 0
for number in lst:
if (number % 2 == 1):
total += number
return total
import time
start_time = time.time()
sum_of_odd_numbers1()
end_time = time.time()
print "Timing of sum_of_odd_numbers1:", end_time - start_time
start_time = time.time()
sum_of_odd_numbers2()
end_time = time.time()
print "Timing of sum_of_odd_numbers2:", end_time - start_time
start_time = time.time()
sum_of_odd_numbers3()
end_time = time.time()
print "Timing of sum_of_odd_numbers3:", end_time - start_time
start_time = time.time()
sumOfOddNumbers()
end_time = time.time()
print "Timing of sumOfOddNumbers:", end_time - start_time
各自輸出:
vivek:~$ python /home/vivek/workspace/vtestproject/study/timer.py
Timing of sum_of_odd_numbers1: 2.4171102047
Timing of sum_of_odd_numbers2: 1.73781108856
Timing of sum_of_odd_numbers3: 2.09230113029
Timing of sumOfOddNumbers: 1.42781090736
爲什麼你這樣標記'python-2.7'和'python-3.x'?你是否真的在兩個版本中遇到同樣的錯誤? – Barmar
什麼是'if(number == count)'?在循環之後,'number'是列表中的最後一個元素,而'count'是偶數的個數。 'number == count'如何告訴你列表中沒有奇數? – Barmar
@Barmar他打算寫'if(count == 0)',但即使如此,'total'總是零,無論如何都是多餘的。 – Selcuk