简体   繁体   English

带有关键字“and”的条件 if 语句给了我意想不到的结果

[英]Conditional if statement with keyword “and” giving me unexpected results

I'm a new programmer so this is probably not efficient but I'm finding this issue curious to me.我是一名新程序员,所以这可能效率不高,但我发现这个问题对我来说很好奇。 Look at the function countDigitsCheck below and notice the if statement is checking if the variable, count_check_one and variable, count_check_two == 1. If they are both == 1 then it multiplies a * b.查看下面的 function countDigitsCheck 并注意 if 语句正在检查变量 count_check_one 和变量 count_check_two == 1。如果它们都是 == 1,则乘以 a * b。 You can see in the output that count_check_one is == 3 (not 1) and count_check_two == 1. Since one of the integers is == 3 the two integers should NOT multiply.您可以在 output 中看到 count_check_one == 3(不是 1)并且 count_check_two == 1。由于其中一个整数是 == 3,因此两个整数不应相乘。 However, you'll notice in the output the integers are multiplying to 900. I understand that if I had used "or" instead of "and" in the if statement I would expect this behavior, but not when I use "and".但是,您会注意到 output 中的整数乘以 900。我知道,如果我在 if 语句中使用“或”而不是“和”,我会期待这种行为,但当我使用“和”时不会。 Please help me to understand why they are still multiplying.请帮助我理解为什么它们仍在成倍增加。 Thanks.谢谢。

def karatsubaAlgorithm(x,y):
  return(countDigitsCheck(x,y))

def countDigitsCheck(one, two):
  count_check_one = countDigits(one)
  count_check_two = countDigits(two)
  a = one
  b = two
  print(count_check_one)
  print(count_check_two)
  if count_check_one and count_check_two == 1:
    answer = a * b
    return(answer)

def countDigits(number):
  Number = number
  Count = 0
  while(Number > 0):
    Number = Number // 10
    Count = Count + 1
  return(Count)

check_function = karatsubaAlgorithm(100,9)
print(check_function)


OUTPUT:
3
1
900

Your if statement is essentially if (count_check_one) and (count_check_two == 1): This means that as long as the value of count_check_one is not 0, the first condition will be true since in Python every integer evaluates to true except 0. If you want to check if both count_check_one and count_check_two are equal to 1, you will have to do if count_check_one == 1 and count_check_two == 1: .您的 if 语句本质上是if (count_check_one) and (count_check_two == 1):这意味着只要 count_check_one 的值不为 0,第一个条件就会为真,因为在 Python 中,每个 integer 评估为真,除了 0。要检查 count_check_one 和 count_check_two 是否都等于 1,您必须执行if count_check_one == 1 and count_check_two == 1: This will check if both variables are 1.这将检查两个变量是否为 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM