好的,我正在为一个项目上课,我坚持这个逻辑错误。我在我的代码中修复了原始错误之后的其他原因......我觉得我知道逻辑错误在哪里。我只是不确定如何解决它。我可以得到一些帮助吗?
提前致谢。
import random
def display_title():
print("Guess the number!")
print()
def set_limit():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
return limit
def count(): ## had to add count being defined as below it was unrecognized by python.
count +=1
def play_game(limit):
global count
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low. ")
count ## See def count
elif guess >= number:
print("Too high. ")
count ## See def count
elif guess == number: ## Pretty sure my logic error is here <----
print("You guessed it in " + str(count) + " tries.\n")
return
def main(): ## syntax error, no : was here
display_title()
again = "y"
while again.lower() == "y":
limit = set_limit()
play_game(limit) ## limit wasn't set inside, causing a missing positional argument
again = input("Play again? (y/n): ")
print()
print("Bye!")
if __name__ == "__main__":
main()
答案 0 :(得分:1)
我有个主意。尝试将上面的&gt; =符号3行更改为&gt;数。因为否则它永远不会到达&#34;如果猜测==数字&#34;因为它会停在&#34;如果猜测&gt; =数字&#34;每次即使猜测是正确的。
这是因为&gt; =表示大于或等于。 我真的希望这会有所帮助。
答案 1 :(得分:0)
print()
打印空行。input
提示用户之前不需要单独的print
声明。count
可以在play_game
内定义,并且应该初始化为1
而不是默认0
,因为即使用户在第一次尝试时猜到他们也有1次猜测elif guess >= number:
需要更改为elif guess > number:
answer
的第一个字符转换为小写等于y
,您可以再次调用main()
重新启动游戏。 我在下面的代码中解决了上述问题:
import random
def display_title():
print("Guess the number!\n")
def set_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
count = 1
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low. ")
count += 1
elif guess > number:
print("Too high. ")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
break
def main():
display_title()
limit = set_limit()
play_game(limit)
again = input("Play again? (y/n): ")
if again[0].lower() == 'y':
main()
else:
print("Bye!")
if __name__ == "__main__":
main()
试试here!