I have a question for you, Python for Moon.

Asked 2 years ago, Updated 2 years ago, 88 views

I brought the For Moon to Gugudan.
When printing from the first stage, I would like to adjust the interval between the steps with interval, first output from the first stage, and lastly output from the 9th stage.
If the interval is 2, 1,3,5,7,9 steps will come out, and if the interval is 7, I want to print it out like 1,8,9 steps!
I wanted to solve the problem with just one basic double for statement, but I couldn't, so I took care of the #last sentence separately.
Can we process one double for statement so that the first step is printed and the last step is 9?
I think there's a way, but it didn't work out, so I'm posting a question ㅠ<

first = 1
last = 9
interval = 7
# Default double for statement
for i in range(first, last+1, interval):
    if i == last:
        continue
    for j in range(1, 10, 1):
        print(i,j,end='  ')
    print()

#Last stage
for i in range(last, last+1, interval):
    for j in range(1, 10, 1):
        print(i,j,end='  ')

python for

2022-09-21 11:47

2 Answers

range(start, stop, step)

step There is a possibility of skipping 9 except for 1 To use it like a question, you need to do a side job that requires another round of 9.

Do the following:

first = 1
last = 9
interval = 3

# Skipping 9 steps is a problem, so set the range that you can get up to 9 steps
for i in range(first, last + 1):
    # Skip the value of i that you do not need through the conditional statement inside the for statement.
    # Let's just leave the code as it for now
    # You can clearly see what you're going to do with the conditional statement
    # It does work, so it's a code that's manageable.
    if i != last and interval != 1 and (i - first) % interval != 0:
        continue
    print(i)

# If you want to use the step value of range(),
# You need to correct the phenomenon of skipping the last.
# Changing the range() end value (stop) adds the last element, which is greater than or equal to the last value.
# You can use this to force the last iteration that was previously missing.
for i in range(first, last + interval, interval):
    # If the last iteration is possible, the last value can be obtained by giving a condition.
    i = i if i < last else last
    # Or
    # # i = min(i, last)
    print(i)


2022-09-21 11:47

first = 1
last = 9
interval = 2

while first != last + interval:
    if first > last:
        first = last
    for j in range(1,10):
        print(first,'*',j,'=',first*j)
    first = first + interval
    print()

This is how you do it.


2022-09-21 11:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.