Python Forum

Full Version: leading zero number formatting
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I want to print out lock combination guesses, all as 4 digits with leading zeros as needed (0000, 0001, 0002, etc.), but I'm having trouble:
#!/usr/bin/env python3 #MoreOnLoops.py #pad lock guesser lockCombo = 1000 guess = 0000 while guess != lockCombo: guess += 1 if guess == lockCombo: print("After " + str(guess) + " guesses, the correct combo is " + str(guess)) break else: print("{:02d}".format(guess)) #print(str(guess) + " is not the correct combo. Trying next guess.") continue
Also, why is 100 not included in the output of the following loop:
for i in range(5, 100, 5):#start at 5, go up to 100 with increments of 5 print(i)
Output:
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95
>>> guess = 0 >>> '{:0>4d}'.format(guess) '0000'
with f-strings in 3.6+
>>> guess = 0 >>> f'{guess:0>4d}' '0000'
(Jan-27-2019, 04:14 PM)RedSkeleton007 Wrote: [ -> ]Also, why is 100 not included in the output of the following loop:
because stop in range(start, stop, step) is not included
(Jan-27-2019, 04:15 PM)buran Wrote: [ -> ]
>>> guess = 0 >>> '{:0>4d}'.format(guess) '0000'

Excellent, but the first printed guess, 0000 did not appear, so I moved the guess incrementor to the else:
#pad lock guesser lockCombo = 1000 guess = 0 #'{:0>4d}'.format(guess)#for python 3 #f'{guess:0>4d}'#for python 3.6+ while guess != lockCombo: #guess += 1 if guess == lockCombo: print("After " + str(guess) + " guesses, the correct combo is " + str(guess)) break else: print('{:0>4d}'.format(guess)) #print('{:0>4d}'.format(guess) + " is not the correct combo. " + # "Trying next guess.") #print(f'{guess:0>4d}' + " is not the correct combo. " + # "Trying next guess.") #print(str(guess) + " is not the correct combo. Trying next guess.") guess += 1 continue
But as a result, the matching 1000 lock combo did not print out:
Output:
0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 <output omitted> 0997 0998 0999
How do I get it to include both the 0000 first guess and the 1000?

(Jan-27-2019, 04:17 PM)buran Wrote: [ -> ]because stop in range(start, stop, step) is not included
Is there a way to get it to print the 100, without having to change stop to 105?