user3370908
user3370908

Reputation: 29

While loop Not Printing Correct Word in Guess game

How do I make the loop work so that it will end when you get it right and ask the question again if you get it wrong? When i guess wrong two or more times it will always say wrong no matter what.

import random;
import sys;
x = random.randint(1, 100);
print(x);
guess = int(input("Guess a number 1 to 100"));
if guess == x:
        print("correct");
        sys.exit()
while guess != x:
    print("wrong");
    int(input("Guess a number 1 to 100"));
    print(x);
    if guess == x:
        print("Correct");
        sys.exit()

Also what function records the number of times it loops. For example if I guess wrong 10 times then I want to print that I scored a 10.

Upvotes: 0

Views: 207

Answers (3)

GLHF
GLHF

Reputation: 4044

Actually you should change your codes to:

import random
x=random.randint(1,100)
score=0
while True:
    guess=int(input("Guess a number 1 to 100: "))
    if guess==x:
        print ("Correct!")
        break
    else:
        print ("Not correct!")
        score+=1
 print ("your answers was wrong {} times.".format(score))

Better statements,less codes. Cheers!

Upvotes: 0

dwn
dwn

Reputation: 563

Missing 'guess=' in the input line in the loop. To record number of times, just increment a variable in the loop.

[ADDENDUM]

import random;
import sys;
x = random.randint(1, 100);
print(x);
count = 1
guess = int(input("Guess a number 1 to 100: "));
while guess != x:
  count += 1
  guess = int(input("Wrong\nGuess a number 1 to 100: "));
print("Correct - score = "+str(100./count)+"%");
sys.exit(0)

Upvotes: 2

Daniel Figueroa
Daniel Figueroa

Reputation: 10686

You have forgotten to assign the second time around to the guess variable

while guess != x:
    print("wrong");
    guess = int(input("Guess a number 1 to 100")); #look here
    print(x);
    if guess == x:
        print("Correct");
        sys.exit()

Upvotes: 2

Related Questions