在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. # eg '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): # +++your code here+++ 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条件中出现错误。 我究竟做错了什么?
 你会想and而不是&& 。 
  Python使用and和or条件。 
即
 if foo == 'abc' and bar == 'bac' or zoo == '123': # do something 
两点评论:
-  在Python中使用and和or进行逻辑运算。
- 使用4个空格来缩进,而不是2个。稍后你会感谢你自己,因为你的代码看起来和其他人的代码几乎一样。 有关更多详细信息,请参阅PEP 8 。
我用一个纯粹的math解决scheme:
 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:] 
 您可以使用and和or执行像C,C ++中的逻辑操作。 像字面意思and是&&和or ||  。 
看看这个有趣的例子,
假设你想用Python构build逻辑门:
 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 
希望这可以帮助!
可能用&代替%更快,更可靠
其他testing甚至/奇数
x是偶数? x%2 == 0
x是奇数? 不是x%2 == 0
也许是更清楚的按位和1
x是奇数? x&1
x是偶数? 不是x&1(不是奇数)
 def front_back(a, b): # +++your code here+++ 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 
在条件中使用“和”。 我在Jupyter Notebook中导入时经常使用这个:
 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() - googlenet_custom_layers.py - GoogLeNet_Inception_v1.py