Python:打印可被x和y整除的范围内的所有数字

时间:2017-07-29 19:33:18

标签: python

我试图打印1-100范围内可被x和y整除的所有数字(即2 nad 3)。现在我有

HTTP_ACCEPT_LANGUAGE

但这不准确,有什么建议吗?

4 个答案:

答案 0 :(得分:3)

(2 and 3)评估为3,这就是为什么你从未看到条件elif x % 3 == 0被执行的原因,请注意输出中没有print("3: ", x)您的代码,因为它已经落入条件if x % (2 and 3) == 0

你最好在那一行使用if ((x % 2) == 0 and (x % 3) == 0) : print("2, 3: ", x)

答案 1 :(得分:3)

它不准确的原因是写x % (2 and 3) python是解释(2和3)。(https://docs.python.org/2/reference/expressions.html

python(2和3)中的

将返回3,因为两个值都是" truthy"当两个项都是True时,python中的AND比较运算符将返回最后一个值。

根据Rajesh Kumar的建议,你可以做到 if x % 6 == 0: # ... 要么 if x % 2 == 0 and x % 3 == 0: # More verbose...

答案 2 :(得分:-1)

如果您有一个号码y和号码x可分割的号码,您可以将其视为: 如果在使用除数y或除数toDivide进行除法后剩下一些休息,则当前考虑的数字x = 2 y = 3 for toDivide in range(1, 101): # can't divide by x and y if toDivide%x and toDivide%y: continue print((str(x)+", "+str(y) if not toDivide%x and not toDivide%y else (str(x) if not toDivide%x else str(y)))+":"+str(toDivide)) 不是您要查找的数字,因为您想要的数字都不是导致休息。

public runLoginProcess(username:String, password:String):Observable<boolean>{

    let body= { "username":username,"password":password };
    let head = new Headers();
    head.append("Content-Type", "application/json");
    head.append("Accept", "application/json");

// RUN THE HTTP CALL AN IF IT WORKS, SEND TRUE AND ERROR IN CASE OF AN ERROR BACK
    return this.http.post("<PATH TO MY SERVICE>", body)
      .map(response => {
          let token = response.json() && response.json().token;
          if (token) {
            localStorage.setItem('currentUser', JSON.stringify({"username": username, "token": token}))
            return true;
          } else {
             return false;
          }
        }
      )
      .catch(err => Observable.of(false)); //this line isn't needed, but just if you don't want to error handle at the caller's subscription, you can intercept them here and map to a false value.
  }
  
  
  
  var loggedIn;
  
   this.runLoginProcess().subscribe(
      (val) => this.loggedIn = val
    );
  
  

编辑:找到并解决了代码错误

答案 3 :(得分:-2)

if x % (2 and 3) == 0中,首先评估(2和3)的值,首先应检查2的可分性,然后检查3.即

if (x % 2) and (x % 3)

括号中的两个表达式返回您最终使用and评估的布尔值。

更正:

for x in range(0, 101):
    if (x % 2) and (x % 3): 
        print("2, 3: ", x)
    elif x % 2 == 0: 
        print("2: ", x)
    elif x % 3 == 0: 
        print("3: ", x)