Python在if語句中與&&(邏輯和)相當


Answers

Python使用andor條件。

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

這是我的代碼:

# 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):
  # +++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條件中出現錯誤。 我究竟做錯了什麼?




在條件中使用“和”。 在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



我採用了一種純粹的數學解決方案:

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:]



您可以使用andor執行像C,C ++中的邏輯操作。 像字面意思and&&or ||

看看這個有趣的例子,

假設你想用Python構建Logic Gates:

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

希望這可以幫助!