0

I am trying to generate 5 unique random numbers and I have written a for loop for it:

for i in range(5):
    print("enter a no")
    x = int(input())
    if x not in a:
        a.append(x)

If x is not in a, only then i should be incremented. I can do this with while loop but want to know if we can do this with a for loop.

1
  • Suppose that the user stubbornly enters the same number over and over again. Then, the program never terminates. On the other hand, any reasonable implementation using a for loop should terminate after finitely many iterations. Commented Jul 31, 2021 at 8:38

3 Answers 3

1

You can do this by converting a range into list. Please follow the given example code.

a = list()
n = 2
myrange = list(range(n)) # converting your range into list
for i in myrange:
    print("enter a no")
    x = int(input())
    if x not in a:
        a.append(x)
    else :
        # add current i again in the rangelist at starting position
        myrange.insert(0,i)
Sign up to request clarification or add additional context in comments.

Comments

0

You can't change how many times for i in range() loop runs. Changing i in the loop has no effect on the range() object.

You can use a nested loop that keeps asking until it gets a number that's not found.

for _ in range(5):
    while True:
        print("enter a no")
        x = int(input())
        if x not in a:
            a.append(x)
            break

1 Comment

"I can do this with while but want to know if we can do this with for" OP mentioned this in the post
0

Here are some approaches:

Option 1 :

Using an infinite value in the range function :

def to_infinity():
    index = 0
    while True:
        yield index
        index += 1

for i in to_infinity():
    print("enter a no")
    x = int(input())
    if len(a) > 5:
        break
    if x not in a:
        a.append(x)

Option 2 :

Using itertools.count:

import itertools
for i in itertools.count(start=1):
    print("enter a no")
    x = int(input())
    if len(a) > 5:
        break
    if x not in a:
        a.append(x)

3 Comments

I think these will not work if the user enters just five different numbers and nothing else. Maybe check for length and break after append instead?
More clearly, you assume that the user will enter at least 6 numbers.
Yes you are right about that @hilberts_drinking_problem If you want make an edit and i'll accept it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.