首页 > 解决方案 > 为什么只是 python 代码中的增强赋值语句会破坏它?

问题描述

为什么这个python代码运行正常,虽然输出不正确

low = 1
high = 1000

print(f"I will guess a value from {low} and {high}"
      "press 'h' or 'l' or 'c'for complete anything else to exit")

guesses = 1 
while True:
    mid = low + (high - low) // 2  
    print("is this is your guess {}".format(mid))
    inp = input()
    if inp == 'h':
        low += 1

    elif inp =='l':
        high -= 1

    elif inp == 'c':
        print('got it')

    else:
        break

但是当我只添加这行代码时,它说语法无效并中断

low = 1
high = 1000

print(f"I will guess a value from {low} and {high}"
      "press 'h' or 'l' or 'c'for complete anything else to exit")

guesses = 1 
while True:
    mid = low + (high - low) // 2  
    print("is this is your guess {}".format(mid))
    inp = input()
    if inp == 'h':
        low += 1

    elif inp =='l':
        high -= 1

    elif inp == 'c':
        print('got it')

    guesses += 1
    else:
        break

那么为什么guesses += 1只是破坏一切它只是一个计数器它在代码中没有任何作用除了计算我循环了多少次

标签: pythonif-statementbinary-search

解决方案


推荐阅读