1

can someone explain how to do this in python? the idea is to figure out the 4 digit code(ex: 3968) entered by the user. how would one design an algorithm to go about finding this? here is what i got..:

code=int(input("Enter 4 digit secret code:"))
count=0000
while(count!=code):
    count=count+1
print("Your code was",count)

this works perfectly....Except when the code starts with 0... Ex: 0387 it prints " Your code was 387" as appose to 0387

whats a quick fix for this?

3MIN3M
  • 69
  • 1
  • 1
  • 9

3 Answers3

5
print("Your code was %04i" % count)

The % means that here comes a variable. The 04 means zero-pad it to four characters. The i means it's an integer. Docs here.

Alternative version, using the new, more flexible .format() formatting:

print("Your code was {:04n}".format(count))
Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
3

You need to print it with some formatting:

print("Your code was {0:04d}".format(count))

which will zero-pad your number up to 4 digits. See the string formatting documentation for more details.

Alternatively, you can use the str.zfill() method to add the extra zeros after string conversion:

print("Your code was", str(count).zfill(4))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Here's a way of doing it purely using strings:

import itertools

code = input("Enter 4 digit secret code:")

for attempt in itertools.product("0123456789", repeat=4):
    attempt = ''.join(attempt)
    if attempt == code:
        print("Your code was", attempt)
        break
Eric
  • 95,302
  • 53
  • 242
  • 374
  • Nope! "count" should be "attempt" in print statement other then that it works although the printed result is a comma separated list.. to fix this i just did this: if j == code: print("Your code was",j) break it now prints it as one string no spaces or commas :D – 3MIN3M Nov 04 '12 at 21:11