我对编程完全陌生。我开始使用最简单的newbs语言,python。我创建了这个简单的猜数字游戏。但我的问题是,当你猜测脚本没有结束的数字时,它就会不断重复。我想知道为什么。谢谢。
P.S。任何其他提示将非常感激,如如何改进编码。请记住,我是一个全新的人,我并不是很了解很多功能,所以要尽可能简单和居高临下(我不介意)。干杯啦! [嗯......我怎么让这个更加变质?我想编辑脚本间距有点不断,因为它需要更加宽泛,所以希望这个额外的文本会让它变得更加分散...只是忽略这部分]
import random
running = True
while running:
guessTaken = 0
print("Hello! What is your name? ")
myName = input()
number = random.randint(0,10)
print("Well, " +myName+ ", I am thinking of a number between 1 and 10.")
print("I'll give you 10 guesses, see if you can guess the number I'm thinking of!")
while guessTaken < 10:
guess = input("Go on! Take a guess: ")
guess = int(guess)
guessTaken += 1
if number > guess:
print("Too low!")
if number < guess:
print("Too high!")
if number == guess:
print("You got it!")
guessTakenstr = str(guessTaken)
print("Good job " +myName+ ", you guessed my number in " +guessTakenstr+ " guesses!")
input("Press <enter> to exit")
running = False
if number != guess:
number = str(number)
print("Sorry, you've had your 10 goes! The number I was think of was " +number)
running = False
答案 0 :(得分:1)
您需要更改条件
while guessTaken < 10:
到
while (guessTaken < 10) and running:
修改强>
添加更多解释。
while
循环将检查条件guessTaken < 10
并继续运行10次,无论您的输入是什么(因为guessTaken
在循环中递增一次)。为了摆脱循环,您需要在此处添加break
语句
if number == guess:
print("You got it!")
guessTakenstr = str(guessTaken)
print("Good job " +myName+ ", you guessed my number in "+guessTakenstr+ " guesses!")
input("Press <enter> to exit")
running = False
break # Break statement added
或者如果用户在我的回答中给出了正确的输入,则需要在进入循环之前(再次)进行检查
while (guessTaken < 10) and running:
答案 1 :(得分:0)
我猜测你的内部while循环的缩进在你的程序中实际上是正确的(也就是它在while running:
循环中缩进了2个空格) -
print("I'll give you 10 guesses, see if you can guess the number I'm thinking of!")
while guessTaken < 10:
否则该程序甚至不会到达猜测数字的部分。
在这种情况下,问题在于你的if部分当数字等于猜测时,即使你正在设置running=False
,你也不会突破内部的while循环,所以你的程序仍会继续直到你进行10次猜测。
此外,从程序看起来你真的不需要外循环,因为经过10次猜测你仍然退出循环(所以它只运行一次迭代),如果是这样,你可以删除它完全循环(while running:
循环)并跳出while guessTaken < 10:
循环。示例 -
guessTaken = 0
print("Hello! What is your name? ")
.
.
while guessTaken < 10:
.
.
if number == guess:
print("You got it!")
guessTakenstr = str(guessTaken)
print("Good job " +myName+ ", you guessed my number in " +guessTakenstr+ " guesses!")
input("Press <enter> to exit")
break
if number != guess:
number = str(number)
print("Sorry, you've had your 10 goes! The number I was think of was " +number)