繁体   English   中英

从 python while 循环得到奇怪和意外的 output

[英]Getting strange and unexpected output from python while loop

我做了一个简单的 while 循环来增加一个数字。 然后我做了一个完全独立的 if 条件来在某些情况下打印语句。 不明白为什么要把这两个放在一起。。。。。

编写一个程序,其输入是两个整数。 Output 第一个 integer 和后续增量 5 只要该值小于或等于第二个 integer。

例如:如果输入是:

-15
10

output 是:

-15 -10 -5 0 5 10 

例如:如果第二个 integer 小于第一个,如:

20
5

output 是:

Second integer can't be less than the first.

为了编码简单,output 在每个 integer 之后有一个空格,包括最后一个。

我的代码:

''' 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

此处显示程序 output

-15 -10 -5 0 5 10 Second integer can't be less than the first.

您的while循环在完成运行时确保firstNum > secondNum 然后,您检查是否firstNum > secondNum (它是),然后您的print语句被执行。

a = int(input())
b = int(input())
if b < a:
    print("Second integer can't be less than the first.")
else:
    while a <= b:
        print(a, end=" ")
        a = a + 5
    print("")

暂无
暂无

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

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