Home > Back-end >  While loops - Can I combine the these loops to create more efficient code?
While loops - Can I combine the these loops to create more efficient code?

Time:11-02

I am working on a basic program to sharpen my skills. I made a program that creates a pin then attempts to crack it. It functions as desired but I'm curious if the last three while loops can be combined into one more efficient loop.

import random

pin = []
pinlength = 0

while pinlength != 3:
    num = random.randint(1,10)
    pin.append(num)
    pinlength =1

print(f"Your pin is {pin}")
find = 0

while find != pin[0]:
    find =1
print(find)
find = 0
while find != pin[1]:
    find =1
print(find)
find = 0
while find != pin[2]:
    find =1
print(find)

CodePudding user response:

Using functions and list comprehensions will make your code clearer and more reusable:

import random

def generate_pin(s: int): 
    return [random.randint(0,9) for _ in range(s)]

def get_ith_digit(pin, ix):
    for n in range(10):
        if n == pin[ix]:
            return n

pin = generate_pin(3)
print(f"this is your pin {pin}")
[get_ith_digit(pin, ix)for ix in range(3)]
  • Related