【问题标题】:Trouble with boolean布尔问题
【发布时间】:2022-01-10 14:24:43
【问题描述】:

我创建了一个非常简单的代码,但在显示它的布尔值时遇到了麻烦。我将放置完整的代码(包括额外的打印,但我的麻烦在于在此处显示 True 或 false:print("Output X is:", AND(a, b))

代码:

#-------------------------|
def AND(a,b):
  
  if a == 1 and b == 1:
    return True
  else:
    return False
#-------------------------|
# main function
    
if __name__=='__main__':
#-------------------------|  Truth Table
  print("--> False | OFF | 0" )
  print("--> True  | ON  | 1" )
  print( )
  print("-------------------------------------")
  print("|     Truth Table for AND gate      |")  
  print("-------------------------------------")
  print("| A = False | B = False | X =",AND(False,False),"| ")
  print("| A = False | B = True  | X =",AND(False,True),"| ")
  print("| A = True  | B = False | X =",AND(True,False),"| ")
  print("| A = True  | B = True  | X =",AND(True,True)," | ")
  print("-------------------------------------")
  print( )
  print("* AND gate output is TRUE only if both inputs are TRUE" )
#-------------------------|
  print( )
  print( )
a= input("Enter a value for input A (0,1): ");
b= input("Enter a value for input B (0,1): ");
print("Output X is:", AND(a, b))

【问题讨论】:

  • 你忘了描述你的“麻烦”。
  • 您正在将整数与字符串进行比较。而True == 1"1" != 1
  • 在您的 input() 前面添加 int(),如下所示:a= int(input("Enter a value for input A (0,1): "))
  • 请不要使用分号。这是unpythonic。
  • 是的。谢谢你,尤金!它现在正在工作

标签: python printing boolean


【解决方案1】:

当您使用“输入”时,它会将其保存为字符串。所以你必须用int(input("Enter a value for input A (0,1): "))把它转换成一个整数。

此外,您的函数AND 中不需要if。见更短的函数AND_V2

def AND(a,b):

    if a == 1 and b == 1:
        return True
    else:
        return False

def AND_V2(a,b):
    # short version of function "AND"
    return a == 1 and b == 1

# main function

print( )
print( )

print("--> False | OFF | 0" )
print("--> True  | ON  | 1" )
print( )
print("-------------------------------------")
print("|     Truth Table for AND gate      |")
print("-------------------------------------")
print("| A = False | B = False | X =",AND(False,False),"| ")
print("| A = False | B = True  | X =",AND(False,True),"| ")
print("| A = True  | B = False | X =",AND(True,False),"| ")
print("| A = True  | B = True  | X =",AND(True,True)," | ")
print("-------------------------------------")
print( )
print("* AND gate output is TRUE only if both inputs are TRUE" )
#-------------------------|
print( )
print( )
a= int(input("Enter a value for input A (0,1): "));
b= int(input("Enter a value for input B (0,1): "));

print("Output X is with V1:", AND(a, b))
print("Output X is with V2:", AND_V2(a, b))

输出:

Enter a value for input A (0,1): >? 1
Enter a value for input B (0,1): >? 1
Output X is with V1: True
Output X is with V2: True

【讨论】:

  • 感谢达曼和加布里埃尔!
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 2019-09-14
  • 2015-05-09
  • 2021-03-06
  • 2015-10-07
  • 2011-08-01
  • 1970-01-01
相关资源
最近更新 更多