如何使循环工作,以便在你正确的时候它会结束,如果你弄错了就再问一遍这个问题? 当我猜错了两次或两次以上时,无论如何都会说错。
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()
还有什么函数记录它循环的次数。例如,如果我猜错了10次,那么我想要打印,我得了10分。
答案 0 :(得分:2)
您忘记第二次分配到guess
变量
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()
答案 1 :(得分:2)
缺少猜测='在循环的输入行中。要记录次数,只需在循环中增加一个变量。
[附录]
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)
答案 2 :(得分:0)
实际上您应该将代码更改为:
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))
更好的陈述,更少的代码。干杯!