Python number matching exit condition question

Asked 2 years ago, Updated 2 years ago, 13 views

In the code that ends only when the number is matched, I added an if statement to end it even if it doesn't meet the conditions of the value I want to enter, but I'm asking because I think only the previous conditions apply.

And how do you use the variables upperbound and lowerbound?

import random
tries=0
num=random.randint(1,100)
print("Guess the number between 1 and 100")
g=int (input ("Enter a number")


while True :
    tries=tries+1
    if g>num:
        g=int("Guess a number less than %d: "%g")
        if g==num and g>num:
           print ("Failed")
           break
        else :
            g=int("Guess a number less than %d: "%g")
    elif g<num:
        g=int("Guess a number greater than %d: "%g")
        if g==num and g<num:
            print ("Failed")
            break
        else :
            g=int("Guess a number greater than %d: "%g")
    else :
        print("Congratulations! Number of attempts =",tries)
        break

python

2022-09-21 10:00

1 Answers

If you look at the code you wrote and summarize what I understood roughly,

Is this right?

It's a bit different from the code you wrote, but I was wondering if you had this intention.

Whatever direction you want, let's take a look at the problem with the code you wrote.

If you look at the if g==num and g>num section, it is true only if the entered number g is equal to the randomly selected number and larger than that number.

That doesn't exist.

Therefore, once you receive the input, you will receive the input one more time no matter of course.

And even though you've obviously had two inputs, you've only had one correct comparison with the correct answer, and the tries are also incremented by one.

Also, you asked how to use the variables upperbound, lowerbound, but it is not determined how to use the variables.

A variable is a variable that can be used by naming a variable.

Maybe you thought of giving conditions using upperbound, lowerbound, but if you do, I recommend you to study each term again.

First, clearly organize what conditions and how they should be executed, and then transfer them to the code.


2022-09-21 10:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.