Home > Net >  How can I create a loop with my conditions
How can I create a loop with my conditions

Time:05-23

i am looking for help. We need to write a program that prints all numbers in the range of (n -20,n 20). In addition, the program asks you beforehand to input a number. If that number is not even or multiple of 10, you need to take a guess again. Only if the number is even and multiple by 10 the program prints the range aforementioned. I struggle with that.

I came up with that solution:

    i = int(input("please enter a number: "))
    while (i % 10 == 0) and ((i % 2) == 0):
        x = 20
        while (x >= 0):
            print(i - x)
            x = x - 1
        break

but it will only print the range n-20 and not 20 and it also won't ask you again if you input a false number.

I know there is also the possibility to use for I in range() but I am at a loss for ideas at the moment.

Thank you!

CodePudding user response:

You can simply do:

while True:
  i = int(input("please enter a number: "))
  if i % 10 == 0:
       for x in range(i-20,i 21):
           print(x)
       break

It will keep on asking until it satisfies the condition.

CodePudding user response:

Better make use of range, something like:

x = 20
for number in range(i - x, i   x   1):
    print(number)

Note: range(1, 5) creates a generator which yields the numbers 1 to 4, excluding 5. Thus the i 20 1.

CodePudding user response:

Doing it the hard way: you want to start from i-20, so:

n = i - 20

and go to i 20, so:

while n < i 20:
    print(n)
    n  = 1

All there is to it.

Or, the easy way, aka one liner using range

print(range(i-20, i 20), sep="\n")

Start with

i = 1
while not (i % 10 == 0):
    i = int(input("please enter a number: "))

to keep asking until valid input is entered and the problem is solved.

  • Related