如何显示循环输入的次数?

时间:2017-03-03 23:26:18

标签: python python-3.x loops while-loop ipython

  1. 要求用户输入2到10之间的整数,将整数分配给变量x。
  2. 当x小于500时,在循环内执行以下操作:

    2.1。打印x的当前值

    2.2。更新x,使其比以前的值加倍

  3. 退出循环后,打印x的最终值和循环输入的次数。

  4. 这就是我所做的我只是不明白如何让python计算循环次数。

    x = int(input("Enter an integer between 2 and 10: "))
    
    while x < 500:
    
        print (x)
    
        x = x+x
    
    print('The final value of x is', x)
    
    print("The loop was entered, )
    

    示例输出:

    Enter an integer between 2 and 10: 10
    10
    20
    40
    80
    160
    320
    The final value of x is 640
    The loop was entered 6 times.
    
    Enter an integer between 2 and 10: 3
    3
    6
    12
    24
    48
    96
    192
    384
    The final value of x is 768
    The loop was entered 8 times.
    

    如果有人可以解释最后一串代码,我将不胜感激!

1 个答案:

答案 0 :(得分:1)

解决方案可以是这样的:

cnt = 0
x = int(input("Enter an integer between 2 and 10: "))
while x < 500:
    print (x)
    x = x+x
    cnt = cnt+1

print('The final value of x is', x)

print('The loop was entered', cnt)