What should I do if I want to create a program that outputs five even numbers starting with 2 in order from the smallest number?I know the code to make it even, but I don't know the future.
n=0
while %2 == 0:
print(n)
n + = 1
Run Results
2
4
6
8
10
In addition to the numbering variable n
, define the variable limit
for how many outputs you want.
Then, increase the limit
variable 1
and turn it in the while
loop.
In other words, while
turns the loop and uses if
to determine even and odd numbers.
n=1
limit = 0
while limit <5:
if n%2 == 0:
print(n)
limit = limit+1
n = n+1
Run Results
2
4
6
8
10
You can use the while loop, but we know that even numbers exist for every two integers and that the fifth even number is 10, so using the for loop is a better prospect.
In addition, Python's range
can pass a third argument to create a skip sequence.
With these, you can write below.
for n in range(2,10+1,2):
print(n)
Unlike this problem, if the conditions are a little more difficult and you don't know when they will be met, it would be easier to write using the while loop as shown in айка <'s answer.
© 2024 OneMinuteCode. All rights reserved.