这里的代码总共实现了它的目的,除了我无法让代码结束并打印“你赢了!”毕竟四个数字都已经猜到了。我们尝试过使用break语句,用“whiles”和“elifs”切换“ifs”以及更改变量
import random
#Gets 4 random single digits to be guesses
n1 = random.randint (0,9)
n2 = random.randint (0,9)
n3 = random.randint (0,9)
n4 = random.randint (0,9)
wrong_guesses = 0
print ("I'm thinking of a 4-digit code. Guess what it is!")
print ("X = wrong guess, O = right guess")
guess = int(input("Enter your 4-number digit here:"))
#Guesses the first (leftmost) number
if guess // 1000 % 10 != n1:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the second (second from the left) number
if guess // 100 % 10 != n2:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the third (second from right) number
if guess // 10 % 10 != n3:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
#Guesses the last (rightmost) number
if guess // 1 % 10 != n4:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if wrong_guesses == 0:
print ("You win!")
while wrong_guesses != 0:
guess = int(input("Enter your 4-digit code here:"))
#Display O if number is correct, X if otherwise
if guess // 1000 % 10 != n1:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 100 % 10 != n2:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 10 % 10 != n3:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess // 1 % 10 != n4:
wrong_guesses +=1
print ('X')
else:
wrong_guesses +=0
print ('O')
if guess == n1 and guess == n2 and guess == n3 and guess == n4:
print ("You win!")
以下是代码无法结束的部分。代码不再显示正确答案的验证,而是继续要求更多数字,如果数字已被猜到则为evem
答案 0 :(得分:0)
我认为问题出在你写的时候:
while wrong_guesses != 0:
guess = int(input("Enter your 4-digit code here:"))
由于您无法在循环中更改wrong_guesses值,因此您将进入无限循环。
我试着通过在这个循环中抛出一些调试打印来验证它,看看是否是这种情况。
另外,不要“尝试使用break语句,切换”ifs“with”whiles“和”elifs“以及更改变量”而不理解你在做什么。
希望这有帮助。