Jade Bell
Jade Bell

Reputation: 41

Where do I need to place the if statement?

I need to print this output:

Guess the price and win the prize!
Enter your guess:46000
Too high!
Enter your guess:45000
Too high!
Enter your guess:44000
Too high!
Enter your guess:43000
Too high!
Enter your guess:42000
Too low!
Enter your guess:42500
Too many guesses!

This is my code:

guess_count = 0
car_price = 42500 

print("Guess the price and win the prize!")
while guess_count <= 5:
   guess_count = guess_count + 1
   guess = int(input("Enter your guess:"))

  if guess == car_price:
    print("You won the car!")
  elif guess < car_price:
    print("Too low!")
  elif guess > car_price:
    print("Too high!")
  if guess_count > 5:
    print("Too many guesses!")

If I input 5 guesses, the code above gives me an output like this:

  Too low!
  Too many guesses!

When a user inputs more than 5 guesses, I just want to print:

  Too many guesses!

What do I need to fix?

Upvotes: 1

Views: 46

Answers (2)

TheSavageTeddy
TheSavageTeddy

Reputation: 204

the code checks the number guessed and then checks how many guesses have been made and if it is over 5 it prints Too many guesses!

try either printing the Too many guesses! text either after the while loop or make it break out of the loop when too many guesses have been made

guess_count = 0
car_price = 42500 

print("Guess the price and win the prize!")
while True:
    guess_count = guess_count + 1
    guess = int(input("Enter your guess:"))

    if guess_count <= 5:
        print("Too many guesses!")
        break
    if guess == car_price:
        print("You won the car!")
        break
    elif guess < car_price:
        print("Too low!")
    elif guess > car_price:
        print("Too high!")

note in the above code I have changed it to be an infinite loop which breaks out after too many guesses and skips over the too low or high text.

Upvotes: 2

Abhishek Rai
Abhishek Rai

Reputation: 2237

In the other answer, if the user enters the CORRECT price..it will still keep asking for guesses which should not happen. No need for infinite loop, this is the right way.Note:- range(n) goes from 0 to n-1

correct = 42500
print("Enter correct amount and win")
for i in range(6):
    guess = int(input("Enter your guess :"))
    if i > 4:
        print("Too many guesses!")
        break
    if guess == correct:
        print("You won")
        break
    elif guess < correct:
        print("Too low")
    else:
        print("Too high!")

Upvotes: 0

Related Questions