我不理解python 3中的代码片段

时间:2019-02-27 11:17:10

标签: python-3.x

我是python的完整入门者。如果这个问题重复出现,或者我看起来像个白痴,我深感抱歉。

high = 100
low = 0
correct = False
response = ""
user_number = input("Please think of a number between 0 and 100!")
while (response != "c"):
    guess = int((high + low)/2)
    print("Is your secret number", guess, "?")
    response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")
    if not  (response == "h" or response == "c" or response == "l"):
        print("Sorry, I did not understand your input.")
    elif (response is "h"):
        high = guess
    elif (response is "l"):
        low = guess

print ("Game over. Your secret number was:", guess)

这是同学的代码。

有人可以向我解释本节的目的吗?我将衷心感谢您的帮助。

correct = False
    response = ""
    user_number = input("Please think of a number between 0 and 100!")
    while (response != "c"):

2 个答案:

答案 0 :(得分:0)

我只能想象这是他退出程序的“关键词”。因此,键入c不会执行任何操作。尽管数字以外的其他内容都会由于第一行执行计算并转换为int

而在此处引发错误

答案 1 :(得分:0)

因此,通常这会要求一个数字(尽管它再也不会使用它了),然后猜测一个数字(在第一次迭代中为50)。询问用户猜测是在初始数字之上还是之下。根据答案,这又是一个猜测。这一直持续到用户输入 c

要解决您更具体的问题:

  • correct = False没用,因为correct变量不再使用

  • response = ""保留用户的输入

  • user_number = input("Please think of a number between 0 and 100!") 获取用户输入。

    • 实际上user_number在其他任何地方都没有使用,因此您只需编写input("Please think ...")
  • while (response != "c")循环播放,直到来自response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly")的用户输入等于 c

希望这会有所帮助。