gpt4 book ai didi

python - 我究竟做错了什么?随机数猜谜游戏

转载 作者:行者123 更新时间:2023-11-28 20:25:25 25 4
gpt4 key购买 nike

首先,非常感谢您提供的任何答案。

无论如何,我是 Python 的初学者,一般来说是编程的初学者。我尝试创建自己的随机数猜测游戏,计算机会在 1-15 之间选择一个随机数,yada yada。

我的问题是,当我试图告诉用户他们的猜测是太低还是太高时,程序要么终止而不通知用户他们是否正确。或者它只是不断循环。

Too Low, please guess again: 14

Correct! You've guessed my number!

Too Low, please guess again: 12

Too Low, please guess again: 1

Too Low, please guess again:

这是我为这个程序编写的全部代码:

import random
from time import sleep

number = random.randint(1,15)
play = input("Hello! Would you like to play (Y/N) ")

if play in('y', 'Y'):
sleep(.75)

print("I've chosen a number between 1 and 15.")
sleep(.5)

guess = int(input("What is my number? "))

while guess >= number:
guess = int(input("Too High, please guess again: "))
if guess == number:
print("Correct! You've guessed my number!")

while guess <= number:
guess = int(input("Too Low, please guess again: "))

if guess == number:
print("Correct! You've guessed my number!")

else:
exit

再次感谢您的回答!

最佳答案

你的循环逻辑有点扭曲。

while guess >= number:
guess = int(input("Too High, please guess again: "))
if guess == number:
print("Correct! You've guessed my number!")

while guess <= number:
guess = int(input("Too Low, please guess again: "))

if guess == number:
print("Correct! You've guessed my number!")
  1. 你在猜测太高时循环。低猜测会打断这一点。
  2. 你在猜测太低时循环。高猜测会打断这一点。

因此,如果我们先进行低猜测,然后进行高猜测,但我们仍然不正确,我们就逃脱了 while配对,不能重试。

相反,试试这个单一的循环结构:

while guess != number:

在里面,if对于 <= , == , 和 >= .干杯!

关于python - 我究竟做错了什么?随机数猜谜游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15261629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com