试着理解我的Python猜谜游戏

2024-05-03 07:03:38 发布

您现在位置:Python中文网/ 问答频道 /正文

作为Python的一部分,我正在做的一个练习是创建一个在终端上运行的猜谜游戏。显然,有多种方法可以做到这一点,而不是简单地看解决方案视频,我试着自己先做。我的代码运行没有错误,据我所知,它应该做的工作,但它没有。而不是只是在这里寻找一个解决方案,重写整个事情只是复制别人做了我想知道是否有人可以帮助我理解为什么我的代码没有做我期望的事情?你知道吗

下面列出了,谢谢。你知道吗

import random

digits = list(range(10))
random.shuffle(digits)
one = digits[0:1]
two = digits[1:2]
three = digits[2:3]

digits = one, two, three

guess = input("What is your guess? ")

g_one = guess[0:1]
g_two = guess[1:2]
g_three = guess[2:3]

while(guess != digits):
    print(digits)
    if(guess == digits):
        print("Congrats, you guessed correctly")
        break
    elif(g_one == one or g_two == two or g_three == three):
        print("One or more of the numbers is correct")
        guess = input("Try again: ")
    elif(g_one != one and g_two != two and g_three != three):
        print("None of those numbers are correct.")
        guess = input("Try again: ")
    else:
        break

Tags: orofinputisrandom解决方案事情one
1条回答
网友
1楼 · 发布于 2024-05-03 07:03:38

似乎您没有在每次迭代中更新g\u one、g\u two和g\u three的值。你知道吗

digits = ([2], [3], [4]) # Assume this is the shuffling result, You are getting a tuple of lists here
guess = input("What is your guess? ") # 123
g_one = guess[0:1] #1
g_two = guess[1:2] #2
g_three = guess[2:3] #3

while(guess != digits): #123 != ([2], [3], [4]) string vs a tuple comparison here
  print(digits)
  if(guess == digits):
    print("Congrats, you guessed correctly")
    break
  elif(g_one == one or g_two == two or g_three == three):
    print("One or more of the numbers is correct")
    guess = input("Try again: ") #You are getting the input but the splits are not updated
  elif(g_one != one and g_two != two and g_three != three):
    print("None of those numbers are correct.")
    guess = input("Try again: ") #Same here. Not updating the splits
  else:
    break

我想这应该可以解释。你知道吗

相关问题 更多 >