Home > OS >  Why does my programm skip a certain print command?
Why does my programm skip a certain print command?

Time:07-24

I'm new to programming, so sorry for the stupid qustion. I'm trying to program a simple guessing game in python and so far it works quite well. The only problem I have is, that if you guess the correct number on your last try, the programm isn't printing the "congrats" command but only the "The Game is Over" command. I'm grateful for any help!

from random import randint

x = randint(1, 20)  
print(x)  
count = int(0)  
t = str(4 - count)  
print("Guessing Game! You have 5 tries to guess a number between 1 and 20!")  
n = int(input("Enter your number: "))

while count <= 3:

    if n < x:
        print(f"{n} is smaller. You have {t} tries left")

    elif n > x:
        print(f"{n} is greater. You have {t} tries left")

    else:
        print("Congrats. You guessed the correct number")
        break
    count  = 1
    t = str(4 - count)
    n = int(input("Enter your number: "))

print("The Game ist Over!")

CodePudding user response:

Your code's problem is in the while condition. It iterates until count = 3 and breaks off the loop without printing "congratz". Meaning that the while loop in your code only iterates 4 times when it should iterate 5 times. Hence, count has to be less than equal to 4 for your code to work properly (One thing to remember is that count is initialized to 0 before it enters the loop for the first time).

while count <= 4:

CodePudding user response:

Here, I've rearranged your code just a bit to make it simpler. You can use a for loop, instead of keeping a count on your own. And this eliminates the unneeded str/int calls.

from random import randint

x = randint(1, 20)  
print(x)  
print("Guessing Game! You have 5 tries to guess a number between 1 and 20!")  

for i in range(5):
    n = int(input("Enter your number: "))
    t = 4-i

    if n < x:
        print(f"{n} is smaller. You have {t} tries left")

    elif n > x:
        print(f"{n} is greater. You have {t} tries left")

    else:
        print("Congrats. You guessed the correct number")
        break

print("The Game ist Over!")

CodePudding user response:

Just for fun, here's what it could look like using a match case statement, and taking advantage of for..else:

from random import randint

low, high = 1, 20
x = randint(low, high)
guesses = 5
print(f"Guessing Game! You have {guesses} tries to guess a number between {low} and {high}!")  

for i in range(1, guesses 1):
    t = guesses-i
    match int(input("Enter your number: ")):
        case n if n < x:
            print(f"{n} is smaller. You have {t} tries left")
        case n if n > x:
            print(f"{n} is greater. You have {t} tries left")
        case _:
            print("Congrats. You guessed the correct number. Good Game!")
            break
else:
    print("The Game is Over! Better Luck Next Time.")
  • Related