【问题标题】:Print even numbers n number of times, using while loop使用while循环打印偶数n次
【发布时间】:2020-11-18 21:01:31
【问题描述】:

任务

编写一个 Python 脚本,它从标准输入中读取一个正整数 n,并输出第一个 n 偶数自然数,每行一个。

(取自然数为1、2、3、4等。)

我是 Python 的初学者,所以我需要使用 while 循环,而不是 forin

我们学到了:

while i < n:
   print i
   i = i + 1

所以这个答案需要一个变体。

【问题讨论】:

  • n = int(input())。祝你好运!
  • Python初学者为什么不能使用for循环?

标签: python loops while-loop


【解决方案1】:

嗨,这段代码应该可以工作!

    n = int(input("Input a number: ")) #Taking in user input to use as n
    
    i = 2 #starting with the first even natural number, which will always be 2

    while i <= n:#while loop will continue until we reach user-inputted n times
        print(i) #will print i (which will be always be 2 for the first round)
        i += 2 #bc you only want even natural numbers, will add 2 to each iteration for even

【讨论】:

    【解决方案2】:

    您需要为每个 i 打印 2 次 i。

    n = int(input())
    
    i = 1
    while i <= n:
       print(2*i)
       i = i + 1
    
    

    【讨论】:

    • 非常感谢!
    【解决方案3】:

    您还可以在循环内通过 % 确定数字是偶数还是奇数

    #take the input
    n = int(input())
    #start the loop
    i = 1
    while i <= n:
       #this condition mean the i is divisable by 2 (is even)
       if i % 2 == 0:
          print(i)
       i = i + 1
    

    此代码将只打印偶数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 1970-01-01
      相关资源
      最近更新 更多