代码之家  ›  专栏  ›  技术社区  ›  skysthelimit91

从python while循环中获得奇怪且意外的输出

  •  0
  • skysthelimit91  · 技术社区  · 2 年前

    我做了一个简单的while循环来增加一个数字。然后我做了一个完全独立的if条件,在特定情况下打印一份声明。我不明白这两个人为什么要结合在一起。。。。。

    写一个输入为两个整数的程序。输出第一个整数 以及随后的增量5,只要该值小于或 等于第二个整数。

    例如:如果输入为:

    -15
    10
    

    输出为:

    -15 -10 -5 0 5 10 
    

    例:如果第二个整数小于第一个整数,如:

    20
    5
    

    输出为:

    Second integer can't be less than the first.
    

    为了简化编码,在每个整数后面输出一个空格,包括 最后一个。

    我的代码:

    ''' Type your code here. '''
    firstNum = int(input())
    secondNum = int(input())
    
    while firstNum <= secondNum:
        print(firstNum, end=" ")
        firstNum +=5
        
    
    
    if firstNum > secondNum:
        print("Second integer can't be less than the first.")
    

    输入程序输入(可选)

    -15
    10
    

    此处显示程序输出

    -15 -10 -5 0 5 10 Second integer can't be less than the first.
    
    1 回复  |  直到 2 年前
        1
  •  2
  •   Josh Clark    2 年前

    你的 while loop正在确保 firstNum > secondNum 当它跑完的时候。然后,你检查一下 firstNum>第二个 print 语句被执行。