Search code examples
pythonbreak

Code before Break Statement in Python not executed


My Programme is a Mastermind Game, sorry for being such a noob :`)

This is my code:

def output(guess, number):
    n=str(number)
    g=str(guess)
    p=""
    if n==g:
        p="Cracked!"
    elif len(n) != len(g):
        p="Enter a " + str(len(n)) + " digit number."
    else:
        for i in range (0,len(n)):
            if g[i] == n[i]:
                p=p+"✔"
            elif g[i] in n:
                p=p+"⭕"
            else:
                p=p+"✖"
    return(p)

import random
turns=0
dig=int(input("Enter the number of digits you want to guess."))
low=10**(dig-1)
up=(10**dig)-1
number = random.randint(low, up)
print("Start Guessing!")
while 1==1:
    guess=input()
    out=output(guess, number)
    print(out)
    turns=turns+1
    if guess==number:
        print("You cracked the number in " + turns + " turns.")
        break

And this is my expected output:

Enter the number of digits you want to guess.3
Start Guessing!
123
✔✖✖
456
✖✖✖
789
✖✖✖
101
✔⭕⭕
110
Cracked!
You cracked the number in 5 turns.

But, this is the actual output:

Enter the number of digits you want to guess.3
Start Guessing!
123
✔✖✖
456
✖✖✖
789
✖✖✖
101
✔⭕⭕
110
Cracked!

My question is, why is the print("You cracked the number in " + turns + " turns.") statement before break not being executed? Is it some bug? Or are there some coding mistakes? Please help.


Solution

  • Try this instead:

    def output(guess, number):
        n=str(number)
        g=str(guess)
        p=""
        if n==g:
            p="Cracked!"
        elif len(n) != len(g):
            p="Enter a " + str(len(n)) + " digit number."
        else:
            for i in range (0,len(n)):
                if g[i] == n[i]:
                    p=p+"✔"
                elif g[i] in n:
                    p=p+"⭕"
                else:
                    p=p+"✖"
        return(p)
    
    import random
    turns=0
    dig=int(input("Enter the number of digits you want to guess."))
    low=10**(dig-1)
    up=(10**dig)-1
    number = random.randint(low, up)
    print("Start Guessing!")
    while 1==1:
        guess=input()
        out=output(guess, number)
        print(out)
        turns=turns+1
        if int(guess)==number:
            print("You cracked the number in", turns, "turns.")
            break
    

    You're mixing up types, there is no way that let's say "123" would be equal to 123.

    Example output:

    Enter the number of digits you want to guess.1
    Start Guessing!
    1
    ✖
    2
    ✖
    3
    ✖
    4
    ✖
    5
    ✖
    6
    ✖
    7
    ✖
    8
    ✖
    9
    Cracked!
    You cracked the number in 9 turns.