简体   繁体   中英

My python code does not run a print statement at the end of a loop

I have this problem when i run the program it all goes good an all, but when a user gets the right answer, the code does not print neither print("Good Job!") or print("Correct"). what is wrong with the code ?

import random

firstNumber = random.randint(1, 50)
secondNumber = random.randint(1, 50)
result = firstNumber + secondNumber
result = int(result)
print("Hello ! What\'s your name ? ")
name = input()
print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))
userAnswer = int(input("Your answer : "))
while (userAnswer != result) :
    if (userAnswer > result) :
        print("Wrong")
    else:
        print("Wrong")
    userAnswer = int(input("Your answer : "))
    if (userAnswer == result):
        print("Correct")
        print("Good Job!")
        break
input("\n\n Press to exit")

The problem is that your while-loop will only run as long as the first answer is wrong. Everything that is indented after while (userAnswer != result) will be ignored by Python if the first answer is right. So logically a first correct answer can never reach print("Correct") , since that would require the answer to be both wrong (to start the while loop) and right (to get to "Correct").

One option is to get rid of the while-loop, and just use if's. You get two chances this way, then you lose.

if (userAnswer == result):
    print("Well done!")
else:
    print("Wrong")
    userAnswer = int(input("Your answer : "))
    if (userAnswer == result):
        print("Correct")
        print("Good Job!")
    else:
        print("Nope all wrong you lose")

Another option is to make an infinite loop using While. (like @csharpcoder said)

while (True) :
    userAnswer = int(input("Your answer : "))
    if (userAnswer == result):
        print("Correct")
        print("Good Job!")
        break
    else:
        print ("Wrong answer")

In the last option a wrong answer gets "Wrong answer" and the while-loop starts again, since True is of course still True. So you try again, until you get the right answer, which will bring you to "correct, good job" and then break (which stops the loop).

I struggled with while-loops and kind of getting it in my head that indentation means Python will treat it as 'one thing' and skip it all if I start it with something that's False.

If the answer is correct, then

while (userAnswer != result) :

will cause the loop contents to be skipped.

How about using a infinite while loop something like this :

while (True) :
    userAnswer = int(input("Your answer : "))
    if (userAnswer == result):
        print("Correct")
        print("Good Job!")
        break
    else:
        print ("Wrong answer")

In your logic if you enter the wrong answer first time and correct answer afterwards , then it will work as per your requirement , but if you enter the correct answer first time it will simple skip the while loop .

First of all, you get input outside of your loop and then don't do anything with it. If your answer is correct on the first try, you will get no output because userAnswer != result will be False immediately and your while loop won't run.

Some other points:

if (userAnswer > result) :
    print("Wrong")
else:
    print("Wrong")

is redundant because you are guaranteed to fall into one of these, as you will only get here if the answer is wrong (and therefore > or < result ). Just print "Wrong" without a condition, as the only reason this would run is if the answer was wrong.

print("Correct")
print("Good Job!")

You can use \\n to print on a new line instead of having multiple print statements together. Usually you only use multiple print s together for readability, but print("Correct\\nGood job!") isn't that much less readable.

if (userAnswer == result):
    #...
    break

You don't need break here because the answer is already correct and the loop won't repeat anyway.

print("Hello !"+" "+ name)
print("Ok !"+" "+ name +" "+ "let\'s start !")
print("What is"+ " " + str(firstNumber) +"+"+ str(secondNumber))

Here, you append string literals to string literals ( "Hello!" + " " ). You don't need to do that as you can just write "Hello! " .

result = firstNumber + secondNumber
result = int(result)

The result (pun not intended) is already an integer, so you don't need to convert it.

I played around a bit to refactor, in an attempt to make it more clear:

import random


name = input("Hello ! What's your name? ")
print("Hello, {name}!".format(name=name))
print("Ok, {name}, let's start!".format(name=name))

first_number = random.randint(1, 50)
second_number = random.randint(1, 50)
correct_answer = first_number + second_number
print("What is, '{first} + {second}'?".format(first=first_number,
                                              second=second_number))
user_answer = None
while user_answer != correct_answer:
    try:
        user_answer = int(input("Your answer : "))  # ValueError will be raised if non integer value given
    except ValueError:
        print("Invalid Input!")
        user_answer = None
    if user_answer:
        if user_answer == correct_answer:
            print("Correct")
            print("Good Job!")
        else:
            print('--> Wrong, try again!')
input("\n<< Press any key to exit >>")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM