0

任务

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

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

我是 Python 的初学者,所以我需要使用while循环,没有foror in

我们学会了:

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

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

4

3 回答 3

2

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

    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
于 2020-11-18T21:20:51.810 回答
1

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

n = int(input())

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

于 2020-11-18T21:09:37.310 回答
0

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

#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

此代码将仅打印偶数

于 2020-11-18T21:36:28.247 回答