# 在if語句中Python等價於&&（邏輯和）

``````# F. front_back
# Consider dividing a string into two halves.
# If the length is even, the front and back halves are the same length.
# If the length is odd, we'll say that the extra char goes in the front half.
# e.g. 'abcde', the front half is 'abc', the back half 'de'.
# Given 2 strings, a and b, return a string of the form
#  a-front + b-front + a-back + b-back
def front_back(a, b):
if len(a) % 2 == 0 && len(b) % 2 == 0:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return``````

IF條件中出現錯誤。 我究竟做錯了什麼？

Python使用`and``or`條件。

``````if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something``````

• 在Python中使用`and``or`進行邏輯運算。
• 使用4個空格來縮進，而不是2個。稍後你會感謝你自己，因為你的代碼看起來和其他人的代碼差不多。 有關更多詳細信息，請參閱PEP 8

``````def front_back(a, b):
return a[:(len(a)+1)//2]+b[:(len(b)+1)//2]+a[(len(a)+1)//2:]+b[(len(b)+1)//2:]``````

``````def front_back(a, b):

if len(a) % 2 == 0 and len(b) % 2 == 0:
print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]

elif len(a) % 2 == 1 and len(b) % 2 == 0:
print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):]

elif len(a) % 2 == 0 and len(b) % 2 == 1:
print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:]

else :
print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]``````

### 看看這個有趣的例子，

``````def AND(a,b):
return (a and b) #using and operator

def OR(a,b):
return (a or b)  #using or operator``````

``````print AND(False, False)
print OR(True, False)``````

### 這將輸出：

``````False
True``````

x是偶數？ x％2 == 0

x是奇數？ 不是x％2 == 0

x是奇數？ x＆1

x是偶數？ 不是x＆1（不是奇數）

``````def front_back(a, b):
if not len(a) & 1 and not len(b) & 1:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return``````

``````def find_local_py_scripts():
import os # does not cost if already imported
for entry in os.scandir('.'):
# find files ending with .py
if entry.is_file() and entry.name.endswith(".py") :
print("- ", entry.name)
find_local_py_scripts()