为什么我得到一个语法错误,我的代码上的最后一个elif语句;我希望它和第一个if语句在同一个块上 &


# import random
# random_number = random.randint(1,1000)
random_number = int(input("Enter a number from 1000"))
guess = 500
high_value = 1000
low_value = 0
guess_counter = 0
if random_number > 500:
for i in range(0,10):
if guess == random_number:
# print("You got it {}".format(guess))
# print(("you got it {}".format(random_number)))
print("The random number was {}".format(random_number))
break
if guess < random_number:
low_value = guess
guess = low_value + (high_value - low_value)//2
high_value = 2*(guess - low_value) + low_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
else:
high_value = guess
guess = low_value + (high_value - low_value)//2
low_value = -2*guess + 2*low_value + high_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
guess = 250
random_number = int(random_number)
elif random_number < 500:
print("hi")

尽量避免出现语法错误。为什么我得到一个语法错误,我的代码上的最后一个elif语句;我想让它和第一个if语句在同一个块上

为您更正,ifelif需要缩进相同:

import random
# random_number = random.randint(1,1000)
random_number = int(input("Enter a number from 1000"))
guess = 500
high_value = 1000
low_value = 0
guess_counter = 0
if random_number > 500:
for i in range(0,10):
if guess == random_number:
# print("You got it {}".format(guess))
# print(("you got it {}".format(random_number)))
print("The random number was {}".format(random_number))
break
if guess < random_number:
low_value = guess
guess = low_value + (high_value - low_value)//2
high_value = 2*(guess - low_value) + low_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
else:
high_value = guess
guess = low_value + (high_value - low_value)//2
low_value = -2*guess + 2*low_value + high_value
guess_counter += 1
print("Guess # {}, your guess was {}".format(guess_counter, guess))
guess = 250
random_number = int(random_number)
elif random_number < 500:
print("hi")

because

guess = 250
random_number = int(random_number)

如果没有indet,这行不能继续,所以你不能在

后面使用elif

您正在获得语法错误,因为guess = 250和random_number = int(random_number)需要缩进。这是基于你正在尝试编写一个数字猜谜游戏的假设,你的代码中也有许多逻辑错误。

相关内容

  • 没有找到相关文章