سؤال

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"  )
هل كانت مفيدة؟

المحلول

In python3, use sep and end parameter in print :

In [4]: for i in range(4):
   ...:     print ("_", sep='', end='')
#output: ____

نصائح أخرى

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top