2

I've written the basic code cracking game (like Hangman) as detailed below but when I run it in Python 3.3.1 the code doesn't appear _ _ _ _ _ as in a game of hangman for example but;

_
_
_
_
_

I would ideally like it to appear in a straight line, I don't have this problem in earlier versions of Python - I've searched and searched and it's slowly driving me crazy - can anyone help please? Then I can look at adding an array to store a series of codes!

Code:

code = "25485"
guesses = ''
turns = 5
counter = 0   

print ("Welcome to code cracker")

while turns > 0:                   

for char in code:      

    if char in guesses:    

        print (char),    

    else:

        print ("_"),     

        counter += 1    

if counter == 0:        
    print ("\nYou cracked the code") 

    break              

print

guess = input("guess a number:") 

guesses += guess                    

if guess not in code:  

    turns -= 1        

    print ("Wrong\n")    

    print ("You have", + turns, 'more guesses')

    if turns == 0:           

        print ("You failed to crack the code\n"  )
  • 1
    I guess in Python3, `print ("_"),` will be a one-elemented tuple holding the result of the `print` function? Use `print("_", end="")` instead. – tobias_k Feb 18 '14 at 15:30
  • See [this question](http://stackoverflow.com/questions/12102749/in-python-3-how-can-i-suppress-the-newline-after-a-print-statement-with-the-comm) – LeartS Feb 18 '14 at 15:32
  • 1
    Could you please fix the indentation of your post? Where does the `while` block end, for example? See [How do I format my code blocks?](http://meta.stackexchange.com/q/22186) for help with that. – Martijn Pieters Feb 18 '14 at 15:33

2 Answers2

4

In python3, use sep and end parameter in print :

In [4]: for i in range(4):
   ...:     print ("_", sep='', end='')
#output: ____
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
2

You can simply avoid printing by joining your chars into one string:

def symbolFor(char):
   if char in guesses:
      return char
   else:
      return "_"

pretty = [symbolFor(char) for char in code]
s = "".join(pretty)
xtofl
  • 40,723
  • 12
  • 105
  • 192
  • Thanks for this solution, I need to keep it as simple as possible but thank you for this solution that I will use later for more complex purposes. Much appreciated. – PythonNewbie Feb 18 '14 at 21:03
  • @PythonNewbie: you're very welcome - this is called a 'list comprehension' and is a very common idiom in Python. – xtofl Feb 19 '14 at 09:09