简体   繁体   中英

Why is this random generator sometimes returning 3 digits instead of 4?

if choice == '1':
    print('Your card has been created')
card = create_card()
print(f'Your card number:\n{card}')
pin = int(''.join(f'{random.randint(0, 9)}' for _ in range(4)))
print(f'Your card PIN:\n{pin}\n')
cards.append([card, pin])

Please can someone explain why the above code sometimes generates a 3-digit number as opposed to a 4-digit number? For example:这里

Others have explained why you sometimes end up with three-digit (or even two- or one-digit) results. You could view this as a formatting problem -- printing a number with leading zeroes to a specified width. Python does have features supporting that.

But I urge you to instead recognize that the problem is really that your data isn't actually a number in the first place. Rather, it is a string of digits, all of which are always significant. The easiest and best thing to do, then, is to simply keep it as a string instead of converting it to a number.

Your random generator is not returning four-digit numbers sometimes since it is putting a zero as the first digit. Numbers like 0322 are created by the random generator and it is being converted to 322. This generator can also make two-digit and one-digit numbers because of the zeros in front. If you want four-digit numbers only use pin = random.randint(1000, 9999) . If you want numbers with leading zeros, use pin = ''.join(f'{random.randint(0, 1)}' for _ in range(4)) . This keeps the leading zeros. Keeping the pin as a string stops the leading zeros from being removed.

In your logic, it's possible to generate a string that starts with 0 . If you pass a leading 0 numeric string to int() , that leading 0 is ignored:

print(int("0999"))

Output

999

To fix this, you could just change the range start value.

pin = int(''.join(f'{random.randint(1, 9)}' for _ in range(4)))

Edit: To prove this to yourself, print both the generated string and the result of the int() function, like below.

for i in range(100):
    st = ''.join(f'{random.randint(0, 9)}' for _ in range(4))
    print(st, int(st))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM